200. Number of Islands
Difficulty: Medium
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:
1 | 11110 |
Answer: 1
Example 2:
1 | 11000 |
Answer: 3
Solution
直接dfs1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40class Solution {
int c = 0;
int w, h;
int[][] v;
public int numIslands(char[][] grid) {
int count = 0;
if(null == grid)return count;
if(grid.length==0)return count;
h = grid.length;
w = grid[0].length;
v = new int[h][w];
for(int i=0;i<h;i++){
for(int j=0;j<w;j++){
if(v[i][j]==0 && grid[i][j]=='1'){
dfs(i, j, grid);
count++;
}
}
}
return count;
}
public void dfs(int i, int j, char[][] grid){
if(!check(i, j))return ;
if(grid[i][j]=='0' || v[i][j]!=0)return ;
v[i][j]=1;
dfs(i+1, j, grid);
dfs(i-1, j, grid);
dfs(i, j+1, grid);
dfs(i, j-1, grid);
}
public boolean check(int i, int j){
if(i>=0&& i<h && j>=0&& j<w)return true;
return false;
}
}