LeetCode | 矩阵置零

552 字
3 分钟
LeetCode | 矩阵置零

分类:数组 / 矩阵

题目#

给定一个 m x n 的矩阵 matrix。如果某个元素为 0,就把它所在的整行和整列都设为 0

要求直接修改原矩阵。

示例:

输入:
[
[1, 1, 1],
[1, 0, 1],
[1, 1, 1]
]
输出:
[
[1, 0, 1],
[0, 0, 0],
[1, 0, 1]
]

讲解#

这道题不能看到 0 就立刻把整行整列改成 0

原因是:新改出来的 0 会影响后面的判断,导致本来不该被清零的位置也被清零。

所以要分两步:

  1. 先记录哪些行、哪些列需要变成 0
  2. 再统一把这些行和列改成 0

这里直接使用标记数组:

  • row_0[row] 表示第 row 行要不要变成 0
  • col_0[col] 表示第 col 列要不要变成 0

先扫描一遍矩阵。只要看到 matrix[row][col] == 0,就把 row_0[row]col_0[col] 标记为 1

再扫描一遍矩阵。如果当前位置的行被标记了,或者列被标记了,就把这个位置改成 0

复杂度:

  • 时间复杂度:O(mn)
  • 空间复杂度:O(m + n)

吐槽: 官方题解还有两个标记变量和一个标记变量的写法,时间复杂度都是 O(mn),空间复杂度可以做到 O(1)。它们会复用矩阵的第一行、第一列做标记,笔者觉得,可读性不如这个版本;实际开发里一般也不至于为了这点空间把代码写得那么绕,所以这里不写。

代码#

源码#

from typing import List
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
m = len(matrix)
n = len(matrix[0])
row_0 = [0] * m
col_0 = [0] * n
for row in range(0,m):
for col in range (0,n):
if matrix[row][col] == 0 :
row_0[row],col_0[col] = 1,1
for row in range(0,m):
for col in range (0,n):
if (row_0[row] or col_0[col]) :
matrix[row][col] = 0

测试#

from src.python._073_Set_Matrix_Zeroes import Solution
sol = Solution()
matrix = [[1, 1, 1], [1, 0, 1], [1, 1, 1]]
assert sol.setZeroes(matrix) is None
assert matrix == [[1, 0, 1], [0, 0, 0], [1, 0, 1]]
matrix = [[0, 1, 2, 0], [3, 4, 5, 2], [1, 3, 1, 5]]
sol.setZeroes(matrix)
assert matrix == [[0, 0, 0, 0], [0, 4, 5, 0], [0, 3, 1, 0]]
matrix = [[1, 0]]
sol.setZeroes(matrix)
assert matrix == [[0, 0]]
matrix = [[1], [0]]
sol.setZeroes(matrix)
assert matrix == [[0], [0]]
print("PASS")

参考资料#

文章分享

如果这篇文章对你有帮助,欢迎分享给更多人!

LeetCode | 矩阵置零
https://leetcode.cn/problems/set-matrix-zeroes/
作者
平昊阳
发布于
2026-07-31
许可协议
CC BY-NC-SA 4.0

评论区

Profile Image of the Author
平昊阳
乘长风,破巨浪, 展鸿图于未央!
--
总访问量
--
访客数
公告
欢迎来到我的个人博客!欢迎关注交流吖!
更多相关公告,见
社交-留言」。
音乐
封面

音乐

暂未播放

0:000:00
暂无歌词
站点统计
文章
66
分类
16
标签
93
总字数
477,284
运行时长
0
最后活动
0 天前

文章目录