题目
法1:岛屿数量
class Solution {
public int numIslands(char[][] grid) {
int m = grid.length, n = grid[0].length;
int[][] used = new int[m][n];
int res = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == '0' || used[i][j] == 1) {
continue;
}
++res;
dfs(i, j, grid, used, m, n);
}
}
return res;
}
public void dfs(int i, int j, char[][] grid, int[][] used, int m, int n) {
if (i < 0 || i >= m
|| j < 0 || j >= n
|| grid[i][j] == '0' || used[i][j] == 1) {
return;
}
used[i][j] = 1;
dfs(i - 1, j, grid, used, m, n);
dfs(i + 1, j, grid, used, m, n);
dfs(i, j - 1, grid, used, m, n);
dfs(i, j + 1, grid, used, m, n);
}
}