LeetCode 题解工作台
01 矩阵
给定一个由 0 和 1 组成的矩阵 mat ,请输出一个大小相同的矩阵,其中每一个格子是 mat 中对应位置元素到最近的 0 的距离。 两个相邻元素间的距离为 1 。 示例 1: 输入: mat = [[0,0,0],[0,1,0],[0,0,0]] 输出: [[0,0,0],[0,1,0],[0,…
4
题型
6
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们创建一个大小和 一样的矩阵 ,并将所有的元素初始化为 。 然后我们遍历 ,将所有的 元素的坐标 $(i, j)$ 加入队列 ,并将 设为 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给定一个由 0 和 1 组成的矩阵 mat ,请输出一个大小相同的矩阵,其中每一个格子是 mat 中对应位置元素到最近的 0 的距离。
两个相邻元素间的距离为 1 。
示例 1:

输入:mat = [[0,0,0],[0,1,0],[0,0,0]] 输出:[[0,0,0],[0,1,0],[0,0,0]]
示例 2:

输入:mat = [[0,0,0],[0,1,0],[1,1,1]] 输出:[[0,0,0],[0,1,0],[1,2,1]]
提示:
m == mat.lengthn == mat[i].length1 <= m, n <= 1041 <= m * n <= 104mat[i][j] is either 0 or 1.mat中至少有一个0
解题思路
方法一:BFS
我们创建一个大小和 一样的矩阵 ,并将所有的元素初始化为 。
然后我们遍历 ,将所有的 元素的坐标 加入队列 ,并将 设为 。
接下来,我们使用广度优先搜索,从队列中取出一个元素 ,并遍历其四个方向,如果该方向的元素 满足 , 且 ,则将 设为 ,并将 加入队列 。
最后返回 。
时间复杂度 ,空间复杂度 。其中 和 分别为矩阵 的行数和列数。
class Solution:
def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:
m, n = len(mat), len(mat[0])
ans = [[-1] * n for _ in range(m)]
q = deque()
for i, row in enumerate(mat):
for j, x in enumerate(row):
if x == 0:
ans[i][j] = 0
q.append((i, j))
dirs = (-1, 0, 1, 0, -1)
while q:
i, j = q.popleft()
for a, b in pairwise(dirs):
x, y = i + a, j + b
if 0 <= x < m and 0 <= y < n and ans[x][y] == -1:
ans[x][y] = ans[i][j] + 1
q.append((x, y))
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate is familiar with state transition dynamic programming techniques and can efficiently apply BFS for this type of problem.
- question_mark
Candidate demonstrates an understanding of matrix-based problems and can optimize for large input sizes.
- question_mark
Candidate can explain the trade-offs between time and space complexity in relation to solving matrix problems like '01 Matrix'.
常见陷阱
外企场景- error
Misunderstanding the problem by treating it as a simple DFS or greedy problem instead of applying dynamic programming and BFS.
- error
Not accounting for large input sizes, which could lead to inefficient solutions or memory overflows.
- error
Incorrectly handling edge cases, such as matrices where zeros are scattered in non-trivial patterns.
进阶变体
外企场景- arrow_right_alt
Solving the problem in a 3D matrix or with different distances (e.g., diagonal moves).
- arrow_right_alt
Handling non-square matrices or matrices with more complex patterns of zeros.
- arrow_right_alt
Optimizing for cases with only one zero in a massive matrix.