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,…

category

4

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 状态·转移·动态规划

bolt

答案摘要

我们创建一个大小和 一样的矩阵 ,并将所有的元素初始化为 。 然后我们遍历 ,将所有的 元素的坐标 $(i, j)$ 加入队列 ,并将 设为 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个由 01 组成的矩阵 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.length
  • n == mat[i].length
  • 1 <= m, n <= 104
  • 1 <= m * n <= 104
  • mat[i][j] is either 0 or 1.
  • mat 中至少有一个
lightbulb

解题思路

方法一:BFS

我们创建一个大小和 mat\textit{mat} 一样的矩阵 ans\textit{ans},并将所有的元素初始化为 1-1

然后我们遍历 mat\textit{mat},将所有的 00 元素的坐标 (i,j)(i, j) 加入队列 q\textit{q},并将 ans[i][j]\textit{ans}[i][j] 设为 00

接下来,我们使用广度优先搜索,从队列中取出一个元素 (i,j)(i, j),并遍历其四个方向,如果该方向的元素 (x,y)(x, y) 满足 0x<m0 \leq x < m, 0y<n0 \leq y < nans[x][y]=1\textit{ans}[x][y] = -1,则将 ans[x][y]\textit{ans}[x][y] 设为 ans[i][j]+1\textit{ans}[i][j] + 1,并将 (x,y)(x, y) 加入队列 q\textit{q}

最后返回 ans\textit{ans}

时间复杂度 O(m×n)O(m \times n),空间复杂度 O(m×n)O(m \times n)。其中 mmnn 分别为矩阵 mat\textit{mat} 的行数和列数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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'.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

01 矩阵题解:状态·转移·动态规划 | LeetCode #542 中等