- 算法
深度优先搜索 - 核心思想
简单的深度优先搜索,每次搜索就发现一个岛屿。这个解法是岛屿题的通解题。 - 代码
class Solution {
public int numIslands(char[][] grid) {
int nums = 0;
int m = grid.length;
int n = grid[0].length;
for(int i = 0;i < m;++i){
for(int j = 0;j < n;++j){
if(grid[i][j] == '1'){
nums++;
dfs(grid,i,j);
}
}
}
return nums;
}
void dfs(char[][] grid ,int i,int j){
int m =grid.length;
int n = grid[0].length;
if(i < 0 || j < 0 || i >= m || j >= n || grid[i][j]=='0') return;
grid[i][j] = '0';
dfs(grid,i-1,j);
dfs(grid,i+1,j);
dfs(grid,i,j-1);
dfs(grid,i,j+1);
}
}