TikTok 面试真题解析:岛屿数量(Number of Islands)|二维网格 DFS/BFS 高频题

32次阅读
没有评论

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

这道题本质是在二维网格中统计“连通块”的数量。每当遇到一个尚未访问过的“1”,就可以以它为起点做一次 DFS 或 BFS,把与它上下左右相连的所有陆地都标记掉。每启动一次这样的搜索,就代表发现了一座新的岛屿。最终统计启动搜索的次数即可得到答案。

正文完
 0