Description
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: |
解法
典型的地图遍历题,这里可以通过BFS和DFS解题。
BFS:
1 | class Solution { |
特别注意需要再新点入队前将地图中的值置0以避免重复访问死循环!!!
DFS递归解法:
1 | class Solution { |
DFS 栈解法
1 | class Solution { |
同样注意标0的时机。