Complete-Preparation

🎉 One-stop destination for all your technical interview Preparation 🎉

View the Project on GitHub

73. Set Matrix Zeroes 🌟🌟

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.

Brute Force

O(m+n) space optimization

O(1) Space Optimization

Code

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;
        }
    }
};