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"