LeetCode——200. 岛屿数量:
public class Solution {
int tox[] = {-1, 0, 1, 0}; //上 右 下 左
int toy[] = {0, 1, 0, -1};
// int tox[] = {-1, -1, 0, 1, 1, 1, 0, -1}; //上 右上 --顺时针转
// int toy[] = {0, 1, 1, 1, 0, -1, -1, -1};
public int numIslands(char[][] grid) {
int ans = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == '1') {
ans++;
dfs(grid, i, j);
}
}
}
return ans;
}
public void dfs(char[][] grid, int x, int y) {
if (grid[x][y] == '1') {
grid[x][y] = '0';
}
for (int i = 0; i < 4; i++) {
int newx = x + tox[i];
int newy = y + toy[i];
if (newx >= 0 && newx < grid.length && newy >= 0 && newy < grid[0].length) {
if (grid[newx][newy] == '1') {
dfs(grid, newx, newy);
}
}
}
}
}