Given a 2d grid map of
'1'
s (land) and '0'
s (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
11110 11010 11000 00000
Answer: 1
Example 2:
11000 11000 00100 00011
Answer: 3
Answer:
1. Inplace, Time: O(m*n), Space:O(1)
1. Inplace, Time: O(m*n), Space:O(1)
public class Solution {
public int numIslands(char[][] grid) {
if(grid==null)return 0;
int m = grid.length;
if(m==0)return 0;
int n = grid[0].length;
int count=0;
for(int i=0;i<m;++i){
for(int j=0;j<n;++j){
if(grid[i][j]=='1'){
count++;
DFS(grid, i,j);
}
}
}
return count;
}
public void DFS(char[][] grid, int i, int j){
int m=grid.length, n=grid[0].length;
if(i<0||i>=m||j<0||j>=n)return;
if(grid[i][j]!='1'){
return;
}
grid[i][j]='2';
DFS(grid,i-1,j);
DFS(grid,i,j-1);
DFS(grid,i+1,j);
DFS(grid,i,j+1);
return;
}
}
2. Time: O(m*n), Space:O(m*n), using additional boolean[m][n] flag.
public class Solution {
public int numIslands(char[][] grid) {
if(grid==null)return 0;
int m = grid.length;
if(m==0)return 0;
int n = grid[0].length;
int count=0;
boolean[][] flag;
flag = new boolean[m][];
for(int i=0;i<m;++i){
flag[i] = new boolean[n];
for(int j=0;j<n;++j){
flag[i][j]=false;
}
}
for(int i=0;i<m;++i){
for(int j=0;j<n;++j){
if(grid[i][j]=='1' && flag[i][j]==false){
count++;
DFS(grid,i,j,flag);
}
}
}
return count;
}
public void DFS(char[][] grid, int i, int j, boolean[][] flag){
//check valid boundary
int m=grid.length, n=grid[0].length;
if(i<0||i>=m||j<0||j>=n)return;
if(grid[i][j]=='1' && flag[i][j]==false){
flag[i][j]=true;
DFS(grid,i-1,j,flag);
DFS(grid,i,j-1,flag);
DFS(grid,i+1,j,flag);
DFS(grid,i,j+1,flag);
}
return;
}
}
2. Time: O(m*n), Space:O(m*n), using additional boolean[m][n] flag.
public class Solution {
public int numIslands(char[][] grid) {
if(grid==null)return 0;
int m = grid.length;
if(m==0)return 0;
int n = grid[0].length;
int count=0;
boolean[][] flag;
flag = new boolean[m][];
for(int i=0;i<m;++i){
flag[i] = new boolean[n];
for(int j=0;j<n;++j){
flag[i][j]=false;
}
}
for(int i=0;i<m;++i){
for(int j=0;j<n;++j){
if(grid[i][j]=='1' && flag[i][j]==false){
count++;
DFS(grid,i,j,flag);
}
}
}
return count;
}
public void DFS(char[][] grid, int i, int j, boolean[][] flag){
//check valid boundary
int m=grid.length, n=grid[0].length;
if(i<0||i>=m||j<0||j>=n)return;
if(grid[i][j]=='1' && flag[i][j]==false){
flag[i][j]=true;
DFS(grid,i-1,j,flag);
DFS(grid,i,j-1,flag);
DFS(grid,i+1,j,flag);
DFS(grid,i,j+1,flag);
}
return;
}
}
No comments:
Post a Comment