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


本题难度Medium。

DFS

复杂度

时间 O(N) 空间 O(N) 函数调用栈深度

思路

利用DFS对连片的​​'1'​​​进行“传染式”搜索。
在每个点上进行DFS,如果该点为​​​'1'​​​就将其改为​​'0'​​​(标记为搜索过),然后继续在其四个方向上DFS并返回​​true​​​;如果该点越界或​​'0'​​​,则返回​​false​​。

对于island的计数并不在dfs函数内,dfs函数的职责是负责传染并返回结果,而主函数的职责才是根据dfs返回结果负责计数。

代码

public class Solution {
public int numIslands(char[][] grid) {
//require
int m=grid.length;
if(m<1)return 0;
int n=grid[0].length;
int ans=0;
//invariant
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
if(dfs(i,j,grid))ans++;
//ensure
return ans;
}
private boolean dfs(int i,int j,char[][] grid){
int m=grid.length,n=grid[0].length;
//base case
if(i<0||i>=m||j<0||j>=n||grid[i][j]=='0')
return false;

//mark this point
grid[i][j]='0';
//infect the adjacent area
dfs(i-1,j,grid);
dfs(i+1,j,grid);
dfs(i,j-1,grid);
dfs(i,j+1,grid);
return true;
}
}