题目
链接
题解
class Solution {
public int numIslands(char[][] grid) {
int c = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
if (grid[i][j] == '1') {
c++;
dfs(grid, i, j);
}
}
}
return c;
}
/**
* 深搜,从[i, j]开始,将所有相邻的1变成0
*/
private void dfs(char[][] grid, int i, int j) {
if (grid[i][j] != '1') {
return;
} else {
grid[i][j] = '0';
}
if (i - 1 >= 0) {
dfs(grid, i - 1, j);
}
if (i + 1 < grid.length) {
dfs(grid, i + 1, j);
}
if (j - 1 >= 0) {
dfs(grid, i, j - 1);
}
if (j + 1 < grid[i].length) {
dfs(grid, i, j + 1);
}
}
}