1
+ /**
2
+ * Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
3
+ *
4
+ * Follow up:
5
+ *
6
+ * Did you use extra space?
7
+ * A straight forward solution using O(mn) space is probably a bad idea.
8
+ * A simple improvement uses O(m + n) space, but still not the best solution.
9
+ * Could you devise a constant space solution?
10
+ *
11
+ * res.js
12
+ * @authors Joe Jiang (hijiangtao@gmail.com)
13
+ * @date 2017-02-28 13:49:19
14
+ * @version $Id$
15
+ *
16
+ * @param {number[][] } matrix
17
+ * @return {void } Do not return anything, modify matrix in-place instead.
18
+ */
19
+ let setZeroes = function ( matrix ) {
20
+ if ( ! matrix . length ) {
21
+ return ;
22
+ }
23
+
24
+ let rowlen = matrix . length ,
25
+ collen = matrix [ 0 ] . length ,
26
+ rowzero = false ,
27
+ colzero = false ;
28
+
29
+ for ( let i = 0 ; i < rowlen ; i ++ ) {
30
+ for ( let j = 0 ; j < collen ; j ++ ) {
31
+ if ( matrix [ i ] [ j ] === 0 ) {
32
+ matrix [ i ] [ 0 ] = 0 ;
33
+ matrix [ 0 ] [ j ] = 0 ;
34
+
35
+ if ( i === 0 ) {
36
+ rowzero = true ;
37
+ }
38
+ if ( j === 0 ) {
39
+ colzero = true ;
40
+ }
41
+ }
42
+ }
43
+ }
44
+
45
+ for ( let i = 1 ; i < rowlen ; i ++ ) {
46
+ for ( let j = 1 ; j < collen ; j ++ ) {
47
+ if ( matrix [ i ] [ 0 ] === 0 || matrix [ 0 ] [ j ] === 0 ) {
48
+ matrix [ i ] [ j ] = 0 ;
49
+ }
50
+ }
51
+ }
52
+
53
+ if ( rowzero ) {
54
+ for ( let i = 0 ; i < collen ; i ++ ) {
55
+ matrix [ 0 ] [ i ] = 0 ;
56
+ }
57
+ }
58
+ if ( colzero ) {
59
+ for ( let i = 0 ; i < rowlen ; i ++ ) {
60
+ matrix [ i ] [ 0 ] = 0 ;
61
+ }
62
+ }
63
+ } ;
64
+
65
+ // Another solution
66
+ let setZeroes = function ( matrix ) {
67
+ if ( ! matrix . length ) {
68
+ return ;
69
+ }
70
+
71
+ let rowlen = matrix . length ,
72
+ collen = matrix [ 0 ] . length ,
73
+ colzero = false ;
74
+
75
+ for ( let i = 0 ; i < rowlen ; i ++ ) {
76
+ if ( matrix [ i ] [ 0 ] === 0 ) {
77
+ colzero = true ;
78
+ }
79
+ for ( let j = 1 ; j < collen ; j ++ ) {
80
+ if ( matrix [ i ] [ j ] === 0 ) {
81
+ matrix [ i ] [ 0 ] = 0 ;
82
+ matrix [ 0 ] [ j ] = 0 ;
83
+ }
84
+ }
85
+ }
86
+
87
+ for ( let i = rowlen - 1 ; i >= 0 ; i -- ) {
88
+ for ( let j = collen - 1 ; j >= 1 ; j -- ) {
89
+ if ( matrix [ i ] [ 0 ] === 0 || matrix [ 0 ] [ j ] === 0 ) {
90
+ matrix [ i ] [ j ] = 0 ;
91
+ }
92
+ }
93
+
94
+ if ( colzero ) {
95
+ matrix [ i ] [ 0 ] = 0 ;
96
+ }
97
+ }
98
+ } ;
0 commit comments