200. 岛屿数量 + dfs
200. 岛屿数量
LeetCode_200
题目描述
代码实现
class Solution {
int[][] direction = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
int m, n;
public int numIslands(char[][] grid) {
m = grid.length;
n = grid[0].length;
int cnt = 0;
for(int i=0; i<m; i++){
for(int j=0; j < n; j++){
if(grid[i][j] == '1'){
cnt++;
grid[i][j] = '0';
dfs(i, j, grid);
}
}
}
return cnt;
}
public void dfs(int x, int y, char[][] grid){
//遍历四个方向
for(int i=0; i<4; i++){
int dx = x + direction[i][0];
int dy = y + direction[i][1];
if(dx >=0 && dx <m && dy >= 0 && dy < n && grid[dx][dy] == '1'){
grid[dx][dy] = '0';
dfs(dx, dy, grid);
}
}
}
}
Either Excellent or Rusty