반응형
Set Matrix Zeroes
Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's.
You must do it in place.
Example 1:

Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]
Example 2:

Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]
Constraints:
m == matrix.lengthn == matrix[0].length1 <= m, n <= 200-231 <= matrix[i][j] <= 231 - 1
Follow up:
- A straightforward solution using
O(mn)space is probably a bad idea. - A simple improvement uses
O(m + n)space, but still not the best solution. - Could you devise a constant space solution?
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
n, m = len(matrix), len(matrix[0])
tbl = []
for i in range(n) :
for j in range(m) :
if matrix[i][j] == 0 :
tbl.append((i, j))
for i, j in tbl :
for a in range(n) :
matrix[a][j] = 0
for b in range(m) :
matrix[i][b] = 0
return matrix
설명 그대로 구현했다.
- 처음 matrix[i][j] 의 값이 0인 (i, j) 좌표를 tbl에 저장한다.
- tbl에 있는 걸 하나씩 불러온 후 행, 열 순서대로 0을 주입 후 반환.
생각보다 쉬운 문제였다. 더 나은 방법이 있나 찾아보니 다른 분들의 풀이도 크게 다르지 않은 것 같아서 이렇게 정리하면 될 듯 싶다.
반응형
'알고리즘 스터디' 카테고리의 다른 글
| [Leetcode/파이썬] 238. Product of Array Except Self (0) | 2025.12.07 |
|---|---|
| [Leetcode/파이썬] 63. Unique Paths II (0) | 2025.12.07 |
| [백준/파이썬] 17141. 연구소2 (1) | 2025.11.28 |
| [백준/파이썬] 17244. 아맞다우산 (0) | 2025.11.25 |
| [백준/파이썬] 10026. 적록색약 (0) | 2025.11.24 |