Problem overview
The method setZeroes receives an m x n matrix, a vector<vector<int>>, by reference. Wherever a cell holds 0, its whole row and its whole column must become 0. The function changes matrix in place and returns nothing.
Only the zeros present at the start count. A cell that turns into 0 during the process doesn't clear its own row and column. Take this matrix:
0 2 3 4
5 0 7 8
9 10 11 12
Its zeros are at row 0, column 0 and at row 1, column 1. Rows 0 and 1 and columns 0 and 1 are cleared, and the result is:
0 0 0 0
0 0 0 0
0 0 11 12
The cells that only became 0 clear nothing more, so 11 and 12 stay. The statement asks for O(m * n) time and O(m + n) extra space.
Approach: write down the zeros, then clear
The natural first attempt scans the matrix and, on meeting a 0, clears its row and column right away. That fails, because the new zeros look exactly like original ones. When the scan reaches them, they clear their own rows and columns too, and the zeros spread much further than they should. On the first example, which has a single 0 in the middle of a 3 by 3 matrix of ones, this approach gives:
1 0 0
0 0 0
0 0 0
Only the middle row and column should be zero.
The fix is to separate looking from changing. The first pass only reads the matrix and records which rows and which columns contain a zero. The second pass changes cells: a cell becomes 0 when its row or its column was recorded. All the decisions are made before any cell changes, so new zeros can't influence anything.
The records need one flag per row and one per column, which is O(m + n) extra space. The statement's follow-up reaches O(1) by storing those flags in the first row and first column of the matrix itself, but this lesson uses the simpler separate flags.
Step by step
- Read the dimensions. Store
matrix.size()in anintnamedm(rows) andmatrix[0].size()in anintnamedn(columns). Every row has the same length, so the first row tells the column count. - Create the flags.
zeroRowis avector<bool>of sizemandzeroColone of sizen, both filled withfalse.zeroRow[i]says whether rowiheld a zero. - Loop over every cell with
ifrom 0 tom - 1and, inside it,jfrom 0 ton - 1. This first pass changes nothing in the matrix. - Test
matrix[i][j] == 0. - Record it: set
zeroRow[i]andzeroCol[j]totrue. Several zeros can share a row or a column, and marking twice is harmless. - Start the second pass with the same two nested loops. Every zero is recorded now, so cells can change safely.
- Clear the cell when
zeroRow[i] || zeroCol[j]is true, by settingmatrix[i][j]to 0.
The solution in C++
class Solution {
public:
void setZeroes(vector<vector<int>> &matrix) {
int m = matrix.size();
int n = matrix[0].size();
vector<bool> zeroRow(m, false);
vector<bool> zeroCol(n, false);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == 0) {
zeroRow[i] = true;
zeroCol[j] = true;
}
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (zeroRow[i] || zeroCol[j]) {
matrix[i][j] = 0;
}
}
}
}
};
The C++ details worth knowing:
vector<bool>(m, false)createsmelements, allfalse. WritingzeroRow[i] = trueonly works because those elements exist already; indexing never adds elements.vector<bool>is a special case. It packs the booleans into bits to save memory, sozeroRow[i]returns a small proxy object instead of abool&. Assigning to it and reading it in a condition work as usual, which is all this solution needs. Where it matters is code that takes a real reference or address of an element, which doesn't compile forvector<bool>.- The matrix is passed by reference (
&matrix), so the second pass changes the caller's matrix. The function returnsvoidbecause the result is the changed matrix itself. - The values can be any
int. The code only compares with 0 and assigns 0, so negative numbers and extreme values likeINT_MINandINT_MAXcause no overflow.
Complexity
Time is O(m * n). Each pass visits every cell once, and each visit costs O(1).
Extra space is O(m + n). zeroRow has m flags and zeroCol has n. That matches the bound in the statement.
Edge cases and common mistakes
- Clearing while scanning. As shown above, writing zeros during the first pass makes them spread. Keep reading and writing in separate passes.
- No zeros at all. Both flag vectors stay all
false, and the matrix is unchanged.{{1, 2, 3}}stays{{1, 2, 3}}. - A 1 by 1 matrix.
{{5}}stays{{5}}and{{0}}stays{{0}}. - A single column.
{{1}, {0}, {3}}becomes{{0}, {0}, {0}}, because the zero's row is one cell and its column is the whole matrix. - Zeros in the first row or column. With separate flag vectors they need no special handling. They only matter in the
O(1)space follow-up, where the first row and column double as the flag storage. - Swapping
mandn.zeroRowis indexed by the rowiand must havemelements,zeroColbyjwithnelements. Swapped sizes go out of bounds when the matrix isn't square.
Testing
The 3 by 4 matrix {{0, 1, 2, 0}, {3, 4, 5, 2}, {1, 3, 1, 5}} has both zeros in row 0, in columns 0 and 3. The result is:
0 0 0 0
0 4 5 0
0 3 1 0
The 3 by 3 matrix of ones with one 0 in the middle becomes:
1 0 1
0 0 0
1 0 1
