File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -22,6 +22,16 @@ public static void main(String[] args) {
2222 setMatrixZero (matrix );
2323 System .out .println (Arrays .deepToString (matrix ));
2424
25+ matrix = new int [][]{
26+ {1 , 2 , 3 , 5 },
27+ {2 , 4 , 0 , 1 },
28+ {2 , 4 , 2 , 1 },
29+ {0 , 4 , 2 , 1 },
30+ };
31+
32+ setZeros (matrix );
33+ System .out .println (Arrays .deepToString (matrix ));
34+
2535 }
2636
2737 // do it in place
@@ -80,4 +90,31 @@ public static void setMatrixZero(int[][] m) {
8090
8191 return ;
8292 }
93+
94+
95+ // need extra space O(m+n)
96+ public static void setZeros (int [][] matrix ) {
97+ boolean [] row = new boolean [matrix .length ];
98+ boolean [] column = new boolean [matrix [0 ].length ];
99+
100+ // Store the row and column index with value 0
101+ for (int i = 0 ; i < matrix .length ; i ++) {
102+ for (int j = 0 ; j < matrix [0 ].length ;j ++) {
103+ if (matrix [i ][j ] == 0 ) {
104+ row [i ] = true ;
105+ column [j ] = true ;
106+ }
107+ }
108+ }
109+
110+ // Set arr[i][j] to 0 if either row i or column j has a 0
111+ for (int i = 0 ; i < matrix .length ; i ++) {
112+ for (int j = 0 ; j < matrix [0 ].length ; j ++) {
113+ if (row [i ] || column [j ]) {
114+ matrix [i ][j ] = 0 ;
115+ }
116+ }
117+ }
118+ }
119+
83120}
You can’t perform that action at this time.
0 commit comments