File tree Expand file tree Collapse file tree 1 file changed +65
-0
lines changed
Expand file tree Collapse file tree 1 file changed +65
-0
lines changed Original file line number Diff line number Diff line change 1+ """
2+ Problem Link: https://leetcode.com/problems/set-matrix-zeroes/
3+
4+ Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
5+
6+ Example 1:
7+ Input:
8+ [
9+ [1,1,1],
10+ [1,0,1],
11+ [1,1,1]
12+ ]
13+ Output:
14+ [
15+ [1,0,1],
16+ [0,0,0],
17+ [1,0,1]
18+ ]
19+
20+ Example 2:
21+ Input:
22+ [
23+ [0,1,2,0],
24+ [3,4,5,2],
25+ [1,3,1,5]
26+ ]
27+ Output:
28+ [
29+ [0,0,0,0],
30+ [0,4,5,0],
31+ [0,3,1,0]
32+ ]
33+
34+ Follow up:
35+ A straight forward solution using O(mn) space is probably a bad idea.
36+ A simple improvement uses O(m + n) space, but still not the best solution.
37+ Could you devise a constant space solution?
38+ """
39+ class Solution (object ):
40+ def setZeroes (self , matrix ):
41+ """
42+ :type matrix: List[List[int]]
43+ :rtype: void Do not return anything, modify matrix in-place instead.
44+ """
45+ row = len (matrix )
46+ col = len (matrix [0 ])
47+ is_col = False
48+ for i in range (row ):
49+ if matrix [i ][0 ] == 0 :
50+ is_col = True
51+ for j in range (1 ,col ):
52+ if matrix [i ][j ] == 0 :
53+ matrix [0 ][j ] = 0
54+ matrix [i ][0 ] = 0
55+
56+ for i in range (1 ,row ):
57+ for j in range (1 ,col ):
58+ if not matrix [i ][0 ] or not matrix [0 ][j ]:
59+ matrix [i ][j ] = 0
60+ if matrix [0 ][0 ] == 0 :
61+ for j in range (col ):
62+ matrix [0 ][j ] = 0
63+ if is_col :
64+ for i in range (row ):
65+ matrix [i ][0 ] = 0
You can’t perform that action at this time.
0 commit comments