Skip to content

Commit ef7a44e

Browse files
refactor 73
1 parent 50fba53 commit ef7a44e

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

src/main/java/com/fishercoder/solutions/_73.java

+42
Original file line numberDiff line numberDiff line change
@@ -131,4 +131,46 @@ public void setZeroes(int[][] matrix) {
131131
}
132132
}
133133
}
134+
135+
public static class Solution4 {
136+
/**
137+
* Space: O(1)
138+
* credit: https://leetcode.com/problems/set-matrix-zeroes/discuss/26014/Any-shorter-O(1)-space-solution
139+
*/
140+
public void setZeroes(int[][] matrix) {
141+
int col0 = 1;
142+
int m = matrix.length;
143+
int n = matrix[0].length;
144+
/**the first iteration (first nested for loop) is to check from top row to bottom row:
145+
* keep the first column state into variable col0;
146+
* then starting from the second column, check all the rest of the columns and mark its top cell and its most-left cell if it
147+
* s a zero.*/
148+
for (int i = 0; i < m; i++) {
149+
if (matrix[i][0] == 0) {
150+
col0 = 0;
151+
}
152+
153+
for (int j = 1; j < n; j++) {
154+
if (matrix[i][j] == 0) {
155+
matrix[i][0] = 0;
156+
matrix[0][j] = 0;
157+
}
158+
}
159+
}
160+
161+
/**the second iteration (second nested for loop) is to check from bottom row to the top row
162+
* from the right-most column to the second left-most column: as long as its left-most column cell or its top row cell is zero, then set that cell to be zero
163+
* at last, check col0 variable, if it's zero, mark that row cell as zero*/
164+
for (int i = m - 1; i >= 0; i--) {
165+
for (int j = n - 1; j >= 1; j--) {
166+
if (matrix[i][0] == 0 || matrix[0][j] == 0) {
167+
matrix[i][j] = 0;
168+
}
169+
}
170+
if (col0 == 0) {
171+
matrix[i][0] = 0;
172+
}
173+
}
174+
}
175+
}
134176
}

src/test/java/com/fishercoder/_73Test.java

+22
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ public class _73Test {
1010
private static _73.Solution1 solution1;
1111
private static _73.Solution2 solution2;
1212
private static _73.Solution3 solution3;
13+
private static _73.Solution4 solution4;
1314
private static int[][] matrix;
1415
private static int[][] expected;
1516

@@ -18,6 +19,7 @@ public static void setup() {
1819
solution1 = new _73.Solution1();
1920
solution2 = new _73.Solution2();
2021
solution3 = new _73.Solution3();
22+
solution4 = new _73.Solution4();
2123
}
2224

2325
@Test
@@ -80,4 +82,24 @@ public void test3() {
8082
assertArrayEquals(expected, matrix);
8183
}
8284

85+
@Test
86+
public void test4() {
87+
matrix = new int[][]{
88+
{0, 0, 0, 5},
89+
{4, 3, 1, 4},
90+
{0, 1, 1, 4},
91+
{1, 2, 1, 3},
92+
{0, 0, 1, 1}
93+
};
94+
solution4.setZeroes(matrix);
95+
expected = new int[][]{
96+
{0, 0, 0, 0},
97+
{0, 0, 0, 4},
98+
{0, 0, 0, 0},
99+
{0, 0, 0, 3},
100+
{0, 0, 0, 0}
101+
};
102+
assertArrayEquals(expected, matrix);
103+
}
104+
83105
}

0 commit comments

Comments
 (0)