FLAG必经之路

# Number of Islands

Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Example 1:

11110110101100000000

Example 2:

11000110000010000011

Credits:

Special thanks to @mithmatt for adding this problem and creating all test cases.

public class Solution {
public int numIslands(char[][] grid) {
if(grid == null || grid.length == 0) return 0;
int m = grid.length;
int n = grid[0].length;
int count = 0;
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(grid[i][j] == '1'){
count++;
dfs(grid, i, j);
}
}
}
return count;
}

public void dfs(char[][] grid, int i, int j){
if(i<0 || i>=grid.length || j<0 || j>=grid[0].length || grid[i][j] == '0'){
return;
}
if(grid[i][j] == '1'){
grid[i][j] = '2';
dfs(grid, i-1, j);
dfs(grid, i+1, j);
dfs(grid, i, j-1);
dfs(grid, i, j+1);
}
}
}


04-15 1976

03-26 2320

10-08 960

12-16 546

04-19 1707

05-22 8116

04-10 1.8万

04-20 1938

04-05 1560

08-25 4465