给你一个由 '1'
(陆地)和 '0'
(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
输入:grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
输出:1
输入:grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
输出:3
代码实现:
java
class Solution {
public int numIslands(char[][] grid) {
int res = 0;
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[0].length; c++) {
if (grid[r][c] == '1') {
dfs(grid, r, c);
res++;
}
}
}
return res;
}
private void dfs(char[][] grid, int r, int c) {
if (!isInGrid(grid, r, c)) {
return;
}
// if (grid[r][c] == '2') {
// return;
// }
if (grid[r][c] == '0') {
return;
}
grid[r][c] = '0';
dfs(grid, r + 1, c);
dfs(grid, r - 1, c);
dfs(grid, r, c + 1);
dfs(grid, r, c - 1);
}
private boolean isInGrid(char[][] grid, int r, int c) {
return r >= 0 && c >= 0 && r < grid.length && c < grid[0].length;
}
}
原题链接:力扣
视频讲解:岛屿数量_哔哩哔哩_bilibili