TikTok VO 面试真题解析:Max Area of Island(岛屿最大面积)

23次阅读
没有评论

Max Area of Island

You are given an m x n binary matrix grid. An island is a group of 1‘s (representing land) connected 4-directionally (horizontally or vertically). You may assume all four edges of the grid are surrounded by water.

The area of an island is the number of cells with a value 1 in the island.

Return all the pairs of row and col indexes which belong to maximum area of an island in grid.

Input:

grid = [["1","1","1","1","0"],
  ["1","1","0","1","0"],
  ["1","1","0","0","1"],
  ["0","0","1","1","0"]
]

Output:

[[0,0],
  [1,0],
  [2,0],
  [2,1],
  [1,1],
  [0,1],
  [0,2],
  [0,3],
  [1,3]
]

这道题本质上是网格图遍历:把每个值为 1 的格子看成图中的节点,使用 DFS 或 BFS 按上下左右四个方向扩展,找出每一块连通的岛屿,并统计其面积。题目要求返回“面积最大的岛屿”对应的所有坐标,因此需要先完整遍历每个连通块,记录其所有格子;如果当前岛屿面积更大,就更新答案并替换坐标集合。实现时通常会用 visited 或原地标记避免重复访问,整体时间复杂度为 O(mn),适合用深搜 / 广搜解决。

正文完
 0