73: Set-Matrix-Zeroes
Medium
We basically are required to iterate through the matrix at least twice:
Now, in the first iteration, I realised that
if matrix[i][j] == 0
, we could simply convert:
- the value present in the first column (of the
same row),
matrix[i][0]
- the value present in the first row (of the same
column),
matrix[0][j]
and then on our second iteration, we can check if either
matrix[i][0] == 0
or matrix[0][j] == 0
to determine if matrix[i][j]
should be
converted to 0
.
Unfortunately, there does exist the edge case of
matrix[0][0]
as values on the first row and first
column will end up converting it when equal to
0
. Therefore, we can initialize a boolean
col0
to check whether we should convert column
0 to all 0
s.
Code:
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
bool col0 = false;
for (int i = 0; i < matrix.size(); ++i) {
if (matrix[i][0] == 0) {
= true;
col0 }
for (int j = 1; j < matrix[0].size(); ++j) {
if (matrix[i][j] == 0) {
[i][0] = matrix[0][j] = 0;
matrix}
}
}
for (int i = matrix.size()-1; i >= 0; --i) {
for (int j = matrix[0].size()-1; j >= 1; --j) {
if (matrix[i][0] == 0 || matrix[0][j] == 0) {
[i][j] = 0;
matrix}
}
if (col0) {
[i][0] = 0;
matrix}
}
}
};