Question:
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
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
Solution:
与在二维数组中word search有点像 这道题有点像 word search的简化版. 每遇到'1'后, 开始向四个方向 递归搜索. 搜到后变为'0', 因为相邻的属于一个island. 然后开始继续找下一个'1'.
public class Solution {
public int numIslands(char[][] grid) {
//求最大连通子图
int m=grid.length;
if (m==0)
return 0;
int n=grid[0].length;
int res=0;
for(int i=0;i<=m-1;i++)
{
for(int j=0;j<=n-1;j++)
{
if(grid[i][j]=='1')
{
res++;
dfs(grid,i,j,m,n);
}
}
}
return res;
}
void dfs(char[][]grid, int i,int j,int m,int n)
{
if(i>=0 && j>=0 && i<m && j<n&&grid[i][j]=='1')
{
grid[i][j]='0';
dfs(grid,i,j-1,m,n);
dfs(grid,i,j+1,m,n);
dfs(grid,i-1,j,m,n);
dfs(grid,i+1,j,m,n);
}
}
}
如果是求每个连通子图
public class Solution {
public int res=0;
public int numIslands(char[][] grid) {
int m=grid.length;
if(m==0)
return 0;
int n=grid[0].length;
Map<Integer,Integer> map=new HashMap<Integer,Integer>();
for(int i=0;i<=m-1;i++){
for(int j=0;j<=n-1;j++){
if(grid[i][j]=='1'){
res=0;
dfs(i,j,m,n,grid);
System.out.println(res);
if(map.containsKey(res)){
int tmp=map.get(res);
tmp++;
map.put(res,tmp);
}
else
map.put(res,1);
}
}
}
if(map.containsKey(1)) //calculate 每个size的有多少个
return map.get(1);
else
return 999;
}
public void dfs(int i, int j, int m, int n, char[][] grid){
if(i<=m-1&&j<=n-1&&i>=0&&j>=0&&grid[i][j]=='1'){
grid[i][j]='0';
dfs(i-1,j,m,n,grid);
dfs(i+1,j,m,n,grid);
dfs(i,j-1,m,n,grid);
dfs(i,j+1,m,n,grid);
res++;
}
return ;
}
}