简繁EN

LeetCodeNo. 101

[LeetCode with Python] 73. Set Matrix Zeroes

Contents

Problem

Problem page: https://leetcode.com/problems/set-matrix-zeroes/
Topics: Array
Difficulty: Medium
Similar problems: (M) Game of Life

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.

Follow up:
Did you use extra space?
A straight forward solution using O(m**n) 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?


Analysis

The simplest algorithm that came to mind when I saw this problem was to make one m*n pass and, whenever I hit a 0, zero out its row and column. That could mean zeroing out the same elements over and over.
Then I thought I should keep track of which rows and columns to zero out during the pass and do all the zeroing in one go afterward. That meant I needed space to record whether each row and column needed to be zeroed out.
But the problem says I can't use extra space, so the matrix itself is the only place to keep track. If a point satisfies (x,y)=0, I mark (x,0) and (0,y) as 0 to show that column x and row y need to be zeroed out.
But if the first element of the second row is 0, (0,0) gets marked as 0. That would zero out the first row and the first column, even though the first row shouldn't be zeroed out in this case. I use two extra variables to keep track of whether the first row and the first column need to be zeroed out. I spent a long time trying to use the point (m-1,n-1) to get rid of those two extra variables. I couldn't get it to work, but I'll keep thinking about whether it's possible. Still, the problem asks for constant space, so the algorithm I have now already meets the requirement.


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution:
# @param matrix, a list of lists of integers
# RETURN NOTHING, MODIFY matrix IN PLACE.
def setZeroes(self, matrix):
if None == matrix or [ ] == matrix or None == matrix[0] or [ ] == matrix[0]:
return
firstrow_clear = False ###
firstcol_clear = False
len_x = len(matrix)
len_y = len(matrix[0])
for i in range(0, len_x):
for j in range(0, len_y):
if 0 == matrix[i][j]:
matrix[i][0] = 0
matrix[0][j] = 0
if 0 == i:
firstrow_clear = True
if 0 == j:
firstcol_clear = True
for i in range(1, len_x):
if 0 == matrix[i][0]:
for j in range(0, len_y):
matrix[i][j] = 0
for j in range(1, len_y):
if 0 == matrix[0][j]:
for i in range(0, len_x):
matrix[i][j] = 0
if firstcol_clear:
for i in range(1, len_x):
matrix[i][0] = 0
if firstrow_clear:
for j in range(1, len_y):
matrix[0][j] = 0

Article link: https://xnerv.wang/en/leetcode-set-matrix-zeroes/