给定一个2D的格子Map,1 表示陆地 ,0 表示水,计算岛的数量
岛是被水环绕和相邻的陆地水平方向或者垂直方向相连,可以认为岛的边界都是水包围
例子1;
Input:
11110
11010
11000
00000
Output: 1
例子2:
Input:
11000
11000
00100
00011
Output: 3
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);
}
}
网友评论