题目链接:LeeCode200岛屿数量
题目描述:
遍历整个数组,每次遍历到的时候进入深搜,把所有上下左右连着的1都变成0,遍历数组时进入几次就是几个岛屿
class Solution {
int[][] dir=new int[][]{{1,0},{-1,0},{0,1},{0,-1}};
public int numIslands(char[][] grid) {
int ans=0;
int[][] book=new int[grid.length][grid[0].length];
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if(grid[i][j]=='1'&&book[i][j]==0){
//System.out.println(i+"\t"+j);
dfs(grid,book,i,j);
ans++;
}
}
}
return ans;
}
public void dfs(char[][] grid,int[][] book,int x,int y){
if(grid[x][y]=='0')return;
book[x][y]=1;
for (int i = 0; i < dir.length; i++) {
int xx=x+dir[i][0];
int yy=y+dir[i][1];
if(xx<0||yy>= grid[0].length||yy<0||xx>= grid.length||book[xx][yy]!=0)
continue;
dfs(grid, book, xx, yy);
}
}
}