LeetCode 题解工作台
统计子岛屿
给你两个 m x n 的二进制矩阵 grid1 和 grid2 ,它们只包含 0 (表示水域)和 1 (表示陆地)。一个 岛屿 是由 四个方向 (水平或者竖直)上相邻的 1 组成的区域。任何矩阵以外的区域都视为水域。 如果 grid2 的一个岛屿,被 grid1 的一个岛屿 完全 包含,也就是说 g…
5
题型
6
代码语言
3
相关题
当前训练重点
中等 · 图·搜索
答案摘要
我们可以遍历矩阵 `grid2` 中的每一个格子 $(i, j)$,如果该格子为 ,则从该格子开始进行深度优先搜索,将与该格子相连的所有格子的值都置为 ,并记录与该格子相连的所有格子中,`grid1` 中对应格子的值是否为 ,如果为 ,则说明该格子在 `grid1` 中也是一个岛屿,否则不是。最后统计 `grid2` 中子岛屿的数量即可。 时间复杂度 $O(m \times n)$,空间复杂度 $…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 图·搜索 题型思路
题目描述
给你两个 m x n 的二进制矩阵 grid1 和 grid2 ,它们只包含 0 (表示水域)和 1 (表示陆地)。一个 岛屿 是由 四个方向 (水平或者竖直)上相邻的 1 组成的区域。任何矩阵以外的区域都视为水域。
如果 grid2 的一个岛屿,被 grid1 的一个岛屿 完全 包含,也就是说 grid2 中该岛屿的每一个格子都被 grid1 中同一个岛屿完全包含,那么我们称 grid2 中的这个岛屿为 子岛屿 。
请你返回 grid2 中 子岛屿 的 数目 。
示例 1:
输入:grid1 = [[1,1,1,0,0],[0,1,1,1,1],[0,0,0,0,0],[1,0,0,0,0],[1,1,0,1,1]], grid2 = [[1,1,1,0,0],[0,0,1,1,1],[0,1,0,0,0],[1,0,1,1,0],[0,1,0,1,0]] 输出:3 解释:如上图所示,左边为 grid1 ,右边为 grid2 。 grid2 中标红的 1 区域是子岛屿,总共有 3 个子岛屿。
示例 2:
输入:grid1 = [[1,0,1,0,1],[1,1,1,1,1],[0,0,0,0,0],[1,1,1,1,1],[1,0,1,0,1]], grid2 = [[0,0,0,0,0],[1,1,1,1,1],[0,1,0,1,0],[0,1,0,1,0],[1,0,0,0,1]] 输出:2 解释:如上图所示,左边为 grid1 ,右边为 grid2 。 grid2 中标红的 1 区域是子岛屿,总共有 2 个子岛屿。
提示:
m == grid1.length == grid2.lengthn == grid1[i].length == grid2[i].length1 <= m, n <= 500grid1[i][j]和grid2[i][j]都要么是0要么是1。
解题思路
方法一:DFS
我们可以遍历矩阵 grid2 中的每一个格子 ,如果该格子为 ,则从该格子开始进行深度优先搜索,将与该格子相连的所有格子的值都置为 ,并记录与该格子相连的所有格子中,grid1 中对应格子的值是否为 ,如果为 ,则说明该格子在 grid1 中也是一个岛屿,否则不是。最后统计 grid2 中子岛屿的数量即可。
时间复杂度 ,空间复杂度 。其中 和 分别是矩阵 grid1 和 grid2 的行数和列数。
class Solution:
def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int:
def dfs(i: int, j: int) -> int:
ok = grid1[i][j]
grid2[i][j] = 0
for a, b in pairwise(dirs):
x, y = i + a, j + b
if 0 <= x < m and 0 <= y < n and grid2[x][y] and not dfs(x, y):
ok = 0
return ok
m, n = len(grid1), len(grid1[0])
dirs = (-1, 0, 1, 0, -1)
return sum(dfs(i, j) for i in range(m) for j in range(n) if grid2[i][j])
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(m * n) |
| 空间 | O(m * n) |
面试官常问的追问
外企场景- question_mark
Candidate identifies DFS or flood-fill pattern for island detection.
- question_mark
Candidate considers validating island containment against grid1 during traversal.
- question_mark
Candidate tracks visited cells to prevent revisiting and ensures correct sub-island count.
常见陷阱
外企场景- error
Failing to check every cell of grid2 island against grid1 leads to false positives.
- error
Not marking visited cells results in double-counting islands or infinite recursion.
- error
Using BFS without proper containment check may incorrectly include partial overlaps.
进阶变体
外企场景- arrow_right_alt
Using BFS instead of DFS for flood-fill traversal.
- arrow_right_alt
Counting sub-islands when diagonal connections are considered part of islands.
- arrow_right_alt
Extending to 3D grids or multi-layer maps with similar containment logic.