Amazon VO 面试真题解析:Number of Islands|DFS / BFS 岛屿计数

17次阅读
没有评论

Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return 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:

Input: grid = [["1","1","1","1","0"],
  ["1","1","0","1","0"],
  ["1","1","0","0","0"],
  ["0","0","0","0","0"]
]
Output: 1

Example 2:

Input: grid = [["1","1","0","0","0"],
  ["1","1","0","0","0"],
  ["0","0","1","0","0"],
  ["0","0","0","1","1"]
]
Output: 3

这道题本质上是在二维网格中统计连通块的数量。每当遇到一个值为 1 的陆地格子,就说明发现了一座新岛屿,然后用 DFS 或 BFS 把与它上下左右相连的所有陆地全部标记 / 淹没,避免重复计数。最终遍历完整个网格时,累计的次数就是岛屿数量。由于题目给出网格规模可达 300 x 300,使用遍历加搜索的思路既直接又高效,时间复杂度为 O(mn),适合面试中快速实现。

正文完
 0