Set Matrix Zeroes Algorithm

The Set Matrix Zeroes Algorithm is an efficient method for modifying a matrix such that if an element in the matrix is zero, the entire row and column of that element are set to zero. This algorithm is particularly useful in image processing, computer graphics, and numerical simulations, where it can help in simplifying the matrix operations or reducing the complexity of the problem. The main idea behind this algorithm is to traverse the matrix once, find the locations of zeroes, and then use these locations to update the rows and columns accordingly. To implement this algorithm, one can use the first row and first column of the matrix as a marker to identify which rows and columns need to be set to zero. The algorithm starts by iterating through the matrix, and when a zero is found, the corresponding first row and first column element is set to zero. Once the whole matrix has been traversed, a second pass is made in reverse order to set the rows and columns to zero based on the markers in the first row and first column. This approach ensures that the original matrix is not modified prematurely, and the time complexity of the algorithm is O(m*n), where 'm' and 'n' are the number of rows and columns in the matrix, respectively.
class Solution {
public:
    void setZeroes(vector<vector<int>>& matrix) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        if (matrix.empty()) return;
        
        bool rowzero = false;
        bool colzero = false;
        int row = matrix.size();
        int col = matrix[0].size();
        
        for (int i = 0; i < row; i++) {
            if (matrix[i][0] == 0) colzero = true;
        }
        for (int i = 0; i < col; i++) {
            if (matrix[0][i] == 0) rowzero = true;
        }
        for (int i = 1; i < row; i++) {
            for (int j = 1; j < col; j++) {
                if (matrix[i][j] == 0) {
                    matrix[i][0] = matrix[0][j] = 0;
                }
            }
        }
        for (int i = 1; i < row; i++) {
            if (matrix[i][0] == 0) {
                for (int j = 1; j < col; j++)
                    matrix[i][j] = 0;
            }
        }
        for (int j = 1; j < col; j++) {
            if (matrix[0][j] == 0) {
                for (int i = 1; i < row; i++)
                    matrix[i][j] = 0;
            }
        }
        if (rowzero) {
            for (int j = 0; j < col; j++)
                matrix[0][j] = 0;
        }
        if (colzero) {
            for (int i = 0; i < row; i++)
                matrix[i][0] = 0;
        }
    }
};

LANGUAGE:

DARK MODE: