TikTok / VO 面试真题解析:二维数组最大岛屿面积(DFS / BFS)

17次阅读
没有评论

Calculate the Largest Island in a 2D Integer Array

Question description

Suppose there is an n * n two-dimensional image, where 1 represents "land" and 0 represents empty space. Please design an algorithm to calculate the largest piece of land in the image, that is, the sub-image with the most 1s.

For example:

[[0,0,0,0,0,0,0,0,0,0],
[0,1,1,1,0,0,0,1,0,0],
[0,0,1,1,0,0,0,0,0,0],
[0,0,0,1,0,0,0,1,0,0],
[0,0,0,0,0,0,1,0,1,0],
[0,0,0,1,0,0,0,1,0,0],
[0,0,1,1,1,0,0,1,0,0],
[0,1,1,1,1,1,0,1,0,0],
[0,0,1,1,1,0,0,1,0,0],
[0,0,0,0,0,0,0,0,0,0]
]

The largest island is 12.

这道题本质上是“岛屿面积统计”问题:给定一个由 0 和 1 组成的二维网格,把相邻的 1 视为同一块陆地,要求找出最大的连通块大小。常见做法是遍历整个矩阵,遇到未访问的 1 就用 DFS 或 BFS 向四个方向扩展,把整块岛屿的面积累加起来,同时用 visited 数组或原地标记避免重复统计。整题重点在于网格遍历、连通性判断和搜索模板的熟练应用,时间复杂度通常为 O(n^2),适合面试中考察基础图搜索能力。

正文完
 0