题目描述
AC代码
class Solution {
int n,m;
public int numIslands(char[][] grid) {
if(grid.length==0)
return 0;
int res=0;
n=grid.length;m=grid[0].length;
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
if(grid[i][j]=='1')
{
res++;
dfs(grid,i,j);
}
return res;
}
public void dfs(char[][] grid,int sr,int sc){
grid[sr][sc]='0';
int dx[]={-1,0,1,0},dy[]={0,1,0,-1};
for(int i=0;i<4;i++)
{
int x=dx[i]+sr,y=dy[i]+sc;
if(x>=0&&x<n&&y>=0&&y<m&&grid[x][y]=='1')
dfs(grid,x,y);
}
}
}