最简单的DFS必须掌握!!!
class Solution {
public int numIslands(char[][] grid) {
int m = grid.length, n = grid[0].length, ans = 0;
if (m == 0 || n == 0) {
return ans;
}
boolean[][] visited = new boolean[m][n];
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == '1' && !visited[i][j]) {
++ans;
dfs(grid, visited, i, j);
}
}
}
return ans;
}
public void dfs(char[][] grid, boolean[][] visited, int i, int j) {
if (i >= 0 && i < grid.length
&& j >= 0 && j < grid[0].length
&& grid[i][j] == '1'
&& !visited[i][j]) {
visited[i][j] = true;
dfs(grid, visited, i - 1, j);
dfs(grid, visited, i + 1, j);
dfs(grid, visited, i, j + 1);
dfs(grid, visited, i, j - 1);
}
}
}