Given a boolean 2D matrix,0is represented as the sea,1is represented as the island. If two 1 is adjacent, we consider them in the same island. We only consider up/down/left/right adjacent.
private int m,n;
public int numIslands(boolean[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0) {
return 0;
}
int result=0;
m=grid.length;
n=grid[0].length;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(grid[i][j]==true){
result++;
bfs(grid,i,j);
}
}
}
return result;
}
public void bfs(boolean[][] grid,int x,int y){
//first set itself as false
grid[x][y]=false;
LinkedList<Integer> queue=new LinkedList<Integer>();
//transfer two-dimension to one-dimension
int node=x*n+y;
queue.offer(node);
//queue record the "1" and its adjacent node
while(!queue.isEmpty()){
int current=queue.poll();
//switch current to two-dimension
int i=current/n;
int j=current%n;
//check upward if it is "1" set it as "0" and push into queue
if(i>0 && grid[i-1][j]==true){
grid[i-1][j]=false;
queue.offer((i-1)*n+j);
}
//check downward
if(i<m-1 && grid[i+1][j]==true){
grid[i+1][j]=false;
queue.offer((i+1)*n+j);
}
//check left
if(j>0 && grid[i][j-1]==true){
grid[i][j-1]=false;
queue.offer(i*n+j-1);
}
//check right
if(j<n-1 && grid[i][j+1]==true){
grid[i][j+1]=false;
queue.offer(i*n+j+1);
}
}
}