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:
11110
11010
11000
00000
Answer: 1
Example 2:
11000
11000
00100
00011
Answer: 3
一刷
题解:
题目的意思是,连成一片(horizontally or vertically)的land只能算一个island。 思路是,我们通过DFS找到相邻的并且把它们都置为0.
public class Solution {
private int n;
private int m;
public int numIslands(char[][] grid) {
int count = 0;
n = grid.length;
if(n == 0) return 0;
m = grid[0].length;
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
if(grid[i][j] == '1'){
DFSMarking(grid, i, j);
count++;
}
}
}
return count;
}
private void DFSMarking(char[][] grid, int i, int j){
if(i<0 || j<0 ||i>=n ||j>=m || grid[i][j]!='1') return;
grid[i][j] = '0';
DFSMarking(grid, i+1, j);
DFSMarking(grid, i-1, j);
DFSMarking(grid, i, j-1);
DFSMarking(grid, i, j+1);
}
}
二刷
如果找到island,用dfs对周边island都进行标记。
public class Solution {
public int numIslands(char[][] grid) {
if(grid == null || grid.length == 0 || grid[0].length == 0) return 0;
int m = grid.length, n = grid[0].length;
boolean[][] visited = new boolean[m][n];
int res = 0;
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(visited[i][j] || grid[i][j] == '0') continue;
res++;
dfs(i, j, grid, visited);
}
}
return res;
}
private void dfs(int i, int j, char[][] grid, boolean[][] visited){
if(i<0 || i>=grid.length || j<0 || j>=grid[0].length || grid[i][j] == '0' || visited[i][j]) return;
visited[i][j] = true;
dfs(i+1, j, grid, visited);
dfs(i-1, j, grid, visited);
dfs(i, j+1, grid, visited);
dfs(i, j-1, grid, visited);
}
}