C++ constant space solution.


  • 2
    C
    void setZeroes(vector<vector<int>>& matrix) {
        bool firstRow = false;
        for (unsigned int j=0; j<matrix[0].size(); j++)
            if (matrix[0][j]==0)
                firstRow = true;
        for (unsigned int i=1; i<matrix.size(); i++) 
            for (unsigned int j=0; j<matrix[0].size(); j++) 
                if (matrix[i][j]==0)
                    matrix[i][0] = matrix[0][j] = 0;
        for (unsigned int i=1; i<matrix.size(); i++)
            if (matrix[i][0]==0)
                for (unsigned int j=0; j<matrix[0].size(); j++)
                    matrix[i][j] = 0;
        for (unsigned int j=0; j<matrix[0].size(); j++)
            if(matrix[0][j]==0)
                for (unsigned int i=0; i<matrix.size(); i++)
                    matrix[i][j] = 0;
        if (firstRow)
            for (unsigned int j=0; j<matrix[0].size(); j++)
                matrix[0][j] = 0;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.