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返回结果负责计数。
代码