Number of Islands
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
1 | Input: |
Example 2
1 | Input: |
解题思路
深搜或广搜。如果某个点被访问到,将其状态变为 2
,即 grid[i][j]='2'
。深搜,相当于单点搜索,其邻节点不一定会在当前层次被展开,因此不用将邻节点的访问状态立即改变。广搜,相当于多点搜索,其邻节点一定会在当前层次被展开,因此需要将邻节点的访问状态立即改变,防止后续节点被重复加入。
复杂度分析
- 时间复杂度:$O(mn)$,每个点被访问一次。
- 空间复杂度:$O(mn)$,深搜的递归调用栈,广搜的队列。
代码
1 | class Solution_200 { |