public class Solution {
public int numIslands(char[][] grid) {
int result = 0;
if (grid == null || grid.length == 0 || grid[0].length == 0) {
return result;
}
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == '1') {
result++;
dfs(grid, i, j);
}
}
}
return result;
}
private void dfs(char[][] grid, int i, int j) {
if (grid[i][j] != '1') {
return;
}
grid[i][j] = '2';
if (i - 1 >= 0) {
dfs(grid, i - 1, j);
}
if (j - 1 >= 0) {
dfs(grid, i, j - 1);
}
if (i + 1 < grid.length) {
dfs(grid, i + 1, j);
}
if (j + 1 < grid[0].length) {
dfs(grid, i, j + 1);
}
}
}
2016年10月8日星期六
[LeetCode] #200 Number of Islands
订阅:
博文 (Atom)