🎉 One-stop destination for all your technical interview Preparation 🎉
Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0’s, and return the matrix.You must do it in place.
col
variable and set it true
initially. while traversing the array if we got any 0 in first column so we change col = false
.col==false
we set it to 0.class Solution {
public:
void setZeroes(vector<vector<int>>& matrix)
{
int r = matrix.size(), c = matrix[0].size();
bool col = true;
for (int i = 0; i < r; i++) { // Traverse all rows
if (matrix[i][0] == 0) col = false; // if Element of first column is 0, set col = false
for (int j = 1; j < c; j++) // Traverse all col
if (matrix[i][j] == 0) {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
// traverse from backwards
for (int i = r - 1; i >= 0; i--) {
for (int j = c - 1; j >= 1; j--)
if (matrix[i][0] == 0 || matrix[0][j] == 0) // if any marker array has 0 set i,j th Element to 0
matrix[i][j] = 0;
// if col = false, means whole col is 0.
if (col == false) matrix[i][0] = 0;
}
}
};