DFS
class Solution {
public static void f(char[][] grid,boolean[][] isVisited,int i,int j)
{
if(i<0||i>=grid.length||j<0||j>=grid[0].length||grid[i][j]=='0'||isVisited[i][j]) return ;
isVisited[i][j]=true;
f(grid,isVisited,i+1,j);
f(grid,isVisited,i,j+1);
f(grid,isVisited,i-1,j);
f(grid,isVisited,i,j-1);
}
public static int numIslands(char[][] grid)
{
if(grid==null||grid.length==0) return 0;
boolean[][] isVisited=new boolean[grid.length][grid[0].length];
int count=0;
for(int i=0;i<grid.length;i++)
{
for(int j=0;j<grid[0].length;j++)
{
if(grid[i][j]=='1'&&!isVisited[i][j])
{
f(grid,isVisited,i,j);
count++;
}
}
}
return count;
}
}
BFS
public static class Pos{
int i;
int j;
public Pos(int i,int j){
this.i=i;
this.j=j;
}
}
public static int numIslands(char[][] grid){
int count=0;
boolean[][] isVisited=new boolean[grid.length][grid[0].length];
LinkedList<Pos> queue=new LinkedList<>();
for(int i=0;i<grid.length;i++)
{
for(int j=0;j<grid[0].length;j++)
{
if(!isVisited[i][j]&&grid[i][j]=='1')
{
count++;
queue=new LinkedList<>();
queue.addLast(new Pos(i,j));
isVisited[i][j]=true;
while(!queue.isEmpty())
{
Pos position=queue.pollFirst();
int curi=position.i;
int curj=position.j;
//四个方向看是否合法,然后加入到队列中来
//向上
if(curi!=0&&!isVisited[curi-1][curj]&&grid[curi-1][curj]=='1')
{
queue.addLast(new Pos(curi-1,curj));
isVisited[curi-1][curj]=true;
}
//向下
if(curi!=grid.length-1&&!isVisited[curi+1][curj]&&grid[curi+1][curj]=='1')
{
queue.addLast(new Pos(curi+1,curj));
isVisited[curi+1][curj]=true;
}
//向左
if(curj!=0&&!isVisited[curi][curj-1]&&grid[curi][curj-1]=='1')
{
queue.addLast(new Pos(curi,curj-1));
isVisited[curi][curj-1]=true;
}
//向右
if(curj!=grid[0].length-1&&!isVisited[curi][curj+1]&&grid[curi][curj+1]=='1')
{
queue.addLast(new Pos(curi,curj+1));
isVisited[curi][curj+1]=true;
}
}
}
}
}
return count;
}