简繁EN

LeetCodeNo. 101

【LeetCode with Python】 73. Set Matrix Zeroes

目錄

題目

原題頁面:https://leetcode.com/problems/set-matrix-zeroes/
題目型別:Array
難度評價:Medium
類似題目:(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?


分析

看到這題的第一個想到的最簡單的演算法是,做一次m*n的遍歷,每次遇到0,就將所在的行和列的元素給清零了,顯然這樣可能大量的重複清零。
然後想到的是,不應該在遍歷的過程中就開始清零,而是應該記錄下應該清零哪些行和列,這樣再遍歷完成後再一次性地完成清零工作。於是就需要空間來記錄所有行和列是否需要清零。
但是題目又要求不能使用額外空間,於是就只可能用原有的矩陣來進行記錄。如果一個點(x,y)=0,則將(x,0)和(0,y)標記為0,表示第x列和第y行需要清零。
但是,假如第二行的第一個元素是0,則會導致(0,0)標記為0,這樣會使得第一行和第一列被清零,顯然此時第一行被清零是不應該的。我這裡採用的做法是,對於第一行和第一列是否需要清零,用兩個額外的變數來標記。我嘗試了很久,希望能通過使用點(m-1,n-1),從而去除掉這兩個額外變數,但試了很久都沒有實現,以後還會繼續思考是否可行。不過因為題目要求的是常量空間,所以現在這種演算法已經符合要求了。


程式碼

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

本文地址:https://xnerv.wang/zh-tw/leetcode-set-matrix-zeroes/