思路:
// @Title: 岛屿数量 (Number of Islands)
// @Author: qisiii
// @Date: 2024-01-14 21:29:17
// @Runtime: 4 ms
// @Memory: 47.8 MB
// @comment:
// @flag:
class Solution {
public int numIslands(char[][] grid) {
int x = 0, y = 0, max = 0;
while (x < grid.length) {
y=0;
while (y < grid[x].length) {
Integer size = 0;
if (grid[x][y] == '1') {
size = dfs(x, y, grid);
if(size>0){
max++;
}
}
y++;
}
x++;
}
return max;
}
int dfs(int x, int y, char[][] grid) {
int i = 0;
if (x >= grid.length || x < 0 || y >= grid[x].length || y < 0) {
return 0;
}
if (grid[x][y] == '1') {
i = 1;
} else {
return 0;
}
grid[x][y] = '0';
i += dfs(x, y + 1, grid);
i += dfs(x + 1, y, grid);
i += dfs(x, y - 1, grid);
i += dfs(x - 1, y, grid);
return i;
}
}