73: Set-Matrix-Zeroes
Medium
table of contents
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 0s.
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) {
col0 = true;
}
for (int j = 1; j < matrix[0].size(); ++j) {
if (matrix[i][j] == 0) {
matrix[i][0] = matrix[0][j] = 0;
}
}
}
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) {
matrix[i][j] = 0;
}
}
if (col0) {
matrix[i][0] = 0;
}
}
}
};