Set Matrix Zeroes
Turn every row and column that holds a 0 into zeros, using the matrix itself to remember which ones to clear.
Given a grid of integers matrixmatrix
Example 1
Output: [[1, 0, 1], [0, 0, 0], [1, 0, 1]]
Example 2
Output: [[0, 0, 0, 0], [0, 4, 5, 0], [0, 3, 1, 0]]
The Idea
Think of a scorecard where a 0 in any cell cancels everything in its line, both across and down. Rows and columns are counted from 0, with row 0 at the top and column 0 (col 0 for short) on the left. In Example 1 the single 0 sits at row 1, col 1. So all of row 1 and all of col 1 become 0, and the four corner cells keep their 1.
The obvious plan is to scan the cells from the top left and clear a row and a column the moment a 0 turns up. Try it on Example 1. At row 1, col 1 the scan clears row 1 and col 1. The very next cell, row 1, col 2, now holds 0, so the scan clears col 2 as well. The zeros keep spreading, and the grid ends as [[1, 0, 0], [0, 0, 0], [0, 0, 0]]
The trouble is that a 0 written by the scan looks exactly like a 0 that was there from the start. So how can we remember which rows and columns to clear without confusing our own zeros with the real ones? Finish reading first, keep a record, and clear only afterwards. The record needs one tick for each row and one tick for each column.
The grid itself already has room for that record. Row 0 has one cell above every column, and col 0 has one cell beside every row. A 0 at row i, col j can leave its marks there: a 0 in row i, col 0 means "clear row i", and a 0 in row 0, col j means "clear col j".
The panel labelled "start" shows the original 0 in blue, at row 1, col 1. In "after marking", that 0 has left two orange marks: one at row 1, col 0 for its row, and one at row 0, col 1 for its column. In "after clearing", every other cell has looked at the mark at the left end of its row and the mark at the top of its column. The two teal cells, row 1, col 2 and row 2, col 1, had a mark and became 0. The corners had none and kept their 1.
So the matrix carries its own to-do list in its top row and left column. The one catch is that those cells can hold real zeros of their own, as row 0 of Example 2 does.
Solution Approach
The code rests on four choices: a simple record in two extra arrays and its cost, moving that record into row 0 and col 0, keeping their own zeros apart from the marks, and the order of clearing.
Recording first, with two arrays
What is the simplest record that works? Two boolean arrays, one with m entries for the rows and one with n entries for the columns. One pass over the grid ticks the row and column of every 0, and a second pass sets a cell to 0 when its row or column is ticked. That is correct, but it needs m + n extra booleans, which grows with the grid.
Marks in row 0 and col 0
How can the grid hold the ticks instead? For every 0 at row i, col j, with both i and j at least 1, write 0 into row i, col 0 and into row 0, col j. Writing 0 over a cell in the top row or left column loses nothing that matters. That row or column is being cleared anyway, because the 0 at row i, col j shares it.
The real zeros of row 0 and col 0
What about a 0 that was in row 0 or col 0 from the start? Look at Example 2. Row 0 is [0, 1, 2, 0]
The fix is to read row 0 and col 0 before any mark exists, and keep the answers in two booleans. Here they are named firstRowZerofirstColZero
Why not let the corner cell, row 0, col 0, stand for both? Take [[1, 1], [0, 1]][[0, 0], [0, 0]]
The order of clearing
Which cells get cleared first? The inner cells, those with row and column at least 1, go first, because they read their marks from row 0 and col 0. Row 0 and col 0 are cleared last. In Example 2, row 0 must be cleared, and clearing it early would turn every cell in it into 0. Every column would then look marked, and the whole grid would end up as zeros.
Java Solution
The method setZeroesmatrix
- First, store the number of rows in
and the number of columns inm . One loop reads row 0 and setsn if it holds a 0, and a second loop does the same for col 0 withfirstRowZero .firstColZero - Then visit the inner cells with two loops, one inside the other: the outer loop moves
over rows 1 to m - 1, and the inner loop movesi over columns 1 to n - 1. For each 0 found, setj andmatrix[i][0] to 0 as marks.matrix[0][j] - Visit the same inner cells again with a second pair of loops. Set a cell to 0 when the mark for its row,
, or the mark for its column,matrix[i][0] , is 0.matrix[0][j] - Finally, if
is true, set all of row 0 to 0, and iffirstRowZero is true, set all of col 0 to 0. Nothing is returned: the caller sees the answer infirstColZero itself.matrix
A small helper, runsetZeroesmain[[1, 1], [0, 1]]
public class SetMatrixZeroes {
public static void setZeroes(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
boolean firstRowZero = false;
boolean firstColZero = false;
for (int j = 0; j < n; j++) {
firstRowZero |= matrix[0][j] == 0;
}
for (int i = 0; i < m; i++) {
firstColZero |= matrix[i][0] == 0;
}
// Use row 0 and column 0 as marks for the rest of the matrix.
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
if (matrix[i][j] == 0) {
matrix[i][0] = 0; // mark row i
matrix[0][j] = 0; // mark column j
}
}
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
if (matrix[i][0] == 0 || matrix[0][j] == 0) {
matrix[i][j] = 0;
}
}
}
if (firstRowZero) {
for (int j = 0; j < n; j++) {
matrix[0][j] = 0;
}
}
if (firstColZero) {
for (int i = 0; i < m; i++) {
matrix[i][0] = 0;
}
}
}
static void run(String name, int[][] matrix) {
setZeroes(matrix);
System.out.println(name + ":");
for (int[] row : matrix) {
System.out.println(" " + java.util.Arrays.toString(row));
}
}
public static void main(String[] args) {
run("Example 1", new int[][] {{1, 1, 1}, {1, 0, 1}, {1, 1, 1}});
run("Example 2", new int[][] {{0, 1, 2, 0}, {3, 4, 5, 2}, {1, 3, 1, 5}});
run("Zero in column 0 only", new int[][] {{1, 1}, {0, 1}});
run("One column", new int[][] {{1}, {0}, {1}});
run("No zeros", new int[][] {{1, 2}, {3, 4}});
}
}
Running it prints:
Example 1:
[1, 0, 1]
[0, 0, 0]
[1, 0, 1]
Example 2:
[0, 0, 0, 0]
[0, 4, 5, 0]
[0, 3, 1, 0]
Zero in column 0 only:
[0, 1]
[0, 0]
One column:
[0]
[0]
[0]
No zeros:
[1, 2]
[3, 4]
Under "Example 1", the corner cells still hold 1 in [1, 0, 1][[1, 0, 0], [0, 0, 0], [0, 0, 0]]
Under "Zero in column 0 only", the first line is [0, 1][[0, 0], [0, 0]]firstColZero[1, 2][3, 4]
Complexity
A few passes over the grid do the job, and the record lives in the grid itself.
- Time: O(m × n), because the marking pass and the clearing pass each visit the inner cells once, and reading and clearing row 0 and col 0 add at most m + n steps each.
- Space: O(1), because the marks sit in row 0 and col 0 of
, so the only extra memory is two booleans and the loop counters, not the m + n booleans of the two-array record.matrix
Storing notes inside the input array also solves