433. Number of Islands "Lintcode Java"

Source: Internet
Author: User

Description

Given a Boolean 2D matrix, is 0 represented as the sea, is represented as the island 1 . If The 1 is adjacent, we consider them on the same island. We only consider up/down/left/right adjacent.

Find the number of islands.

Example

Given Graph:

[  [1, 1, 0, 0, 0],  [0, 1, 0, 0, 1],  [0, 0, 0, 1, 1],  [0, 0, 0, 0, 0],  [0, 0, 0, 0, 1]]

Return 3 .

Solve the problem: count the number of islands. Because the connected land is an island, when it is determined that one by one squares are land, the lattice around it cannot be repeated, even on land, but should be treated as an ocean (corresponding to the DFS function in the code below). The code is as follows:

 Public classSolution {/**     * @paramgrid:a boolean 2D matrix *@return: An integer*/     Public intNumislands (Boolean[] grid) {        //Write your code here        intres = 0; intm =grid.length; if(M = = 0)            return0; intn = grid[0].length;  for(inti = 0; I < m; i++){             for(intj = 0; J < N; J + +){                if(Grid[i][j] = =true) {res++;                DFS (grid, I, j); }            }        }        returnRes; }     Public voidDfsBoolean[][]grid,intIintj) {        if(I < 0 | | J < 0 | | I >= grid.length | | J >= grid[0].length) {return; }        if(Grid[i][j] = =true) {Grid[i][j]=false; DFS (grid, I-1, J); DFS (grid, I+1, J); DFS (grid, I, J-1); DFS (grid, I, J+1); }    }}

433. Number of Islands "Lintcode Java"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.