题意:给定一个二维数组,找出其中的岛屿
思路:遍历二维数组,遇到“1”结果+1,同时对当前位置进行dfs,把于它相连的所有的"1"都变更为“2”
思想:DFS
复杂度:时间O(n2),空间O(n)
class Solution {
public int numIslands(char[][] grid) {
int m = grid.length;
if(m == 0)
return 0;
int n = grid[0].length;
int cnt = 0;
for(int i=0;i<m;i++) {
for(int j=0;j<n;j++) {
if(grid[i][j] == '1') {
change(i, j, grid, m, n);
cnt++;
}
}
}
return cnt;
}
void change(int i, int j, char[][] grid, int m, int n) {
if(i<0||j<0||i>=m||j>=n||grid[i][j] == '0' || grid[i][j] == '2') {
return;
}
grid[i][j] = '2';
change(i+1, j, grid, m, n);
change(i, j-1, grid, m, n);
change(i-1, j, grid, m, n);
change(i, j+1, grid, m, n);
}
}
网友评论