O(1) Space | C++ | Proper commented Solution


#1

Idea here is to use first col and first row as a marker to whether that row or col is to be replaced by 0’s, but [0][0] is can mean that either first row or first col is to be replaced by 0’s. So keep [0][0] for rows and some other variable for col-0;

Code :
`

void Solution::setZeroes(vector<vector > &A) {

    if(A.size()==0) return;
    int c=0; // to mark whether col 0 is to be replaced and to keep [0][0] a marker for 0th row
    for(int i=0;i<A.size();i++) {
        for(int j=0;j<A[0].size();j++) {
            if(A[i][j]==0) {
                A[i][0] = 3;

                if(j==0) {
                    c = 3;
                } else A[0][j] = 3;
            }
        }
    }
    
    // set all cols to be 0's except col-0 because that contains row info
    for(int i=A[0].size()-1;i>0;i--) {
        if(A[0][i]==3) {
            for(int j=0;j<A.size();j++) A[j][i] = 0;
        }
    }

    // set all rows marked to be 0
    for(int i=A.size()-1;i>=0;i--) {
        if(A[i][0]==3) {
            for(int j=0;j<A[0].size();j++) A[i][j] = 0;
        }
    }
    
    // set first col to 0
    if(c==3) for(int i=0;i<A.size();i++) A[i][0] = 0; // set 0th col
    return;
}`