File tree Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+
3
+ Date: Dec 25, 2014
4
+ Problem: Set Matrix Zeroes
5
+ Difficulty: Medium
6
+ Source: https://oj.leetcode.com/problems/set-matrix-zeroes/
7
+ Notes:
8
+ Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
9
+ Follow up:
10
+ Did you use extra space?
11
+ A straight forward solution using O(mn) space is probably a bad idea.
12
+ A simple improvement uses O(m + n) space, but still not the best solution.
13
+ Could you devise a constant space solution?
14
+
15
+ Solution: Use first row and column as auxiliary spaces instead of newly allocating ones.
16
+ */
17
+ public class Solution {
18
+ public void setZeroes (int [][] matrix ) {
19
+ int m = matrix .length ;
20
+ if (m <= 0 ) return ;
21
+ int n = matrix [0 ].length ;
22
+
23
+ boolean row_has_zero = false ;
24
+ boolean col_has_zero = false ;
25
+
26
+ for (int j =0 ; j <n ;j ++){
27
+ if (matrix [0 ][j ]==0 ){
28
+ row_has_zero = true ;
29
+ break ;
30
+ }
31
+ }
32
+ for (int i =0 ; i <m ;i ++){
33
+ if (matrix [i ][0 ]==0 ){
34
+ col_has_zero = true ;
35
+ break ;
36
+ }
37
+ }
38
+
39
+ for (int i =0 ;i <m ;i ++){
40
+ for (int j =0 ;j <n ;j ++){
41
+ if (matrix [i ][j ]==0 ){
42
+ matrix [0 ][j ] =0 ;
43
+ matrix [i ][0 ] =0 ;
44
+ }
45
+ }
46
+ }
47
+ for (int i = 1 ; i < m ; i ++)
48
+ for (int j = 1 ; j < n ; j ++)
49
+ if (matrix [i ][0 ] == 0 || matrix [0 ][j ] == 0 )
50
+ matrix [i ][j ] = 0 ;
51
+
52
+ if (row_has_zero )
53
+ for (int i = 0 ; i < n ; i ++)
54
+ matrix [0 ][i ] = 0 ;
55
+ if (col_has_zero )
56
+ for (int i = 0 ; i < m ; i ++)
57
+ matrix [i ][0 ]=0 ;
58
+
59
+ }
60
+ }
You can’t perform that action at this time.
0 commit comments