Friday, October 10, 2014

[Leetcode] Set Matrix Zeroes

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
Follow up:
Did you use extra space?
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?

void setZeroes(vector<vector<int> > &matrix) {
        //borrow first row and first column as the temporary storage to indicate whether this row/col need to be zeroed
        //use two flag to indicate whether first row/col need to be zeroed 
        bool firstRowZero = false;
        bool firstColZero = false;
        for(int i=0; i<matrix.size(); i++)
        {
            for(int j=0; j<matrix[0].size(); j++)
            {
                if (matrix[i][j] == 0)
                {
                    //0 in the first row
                    if (i == 0)
                        firstRowZero = true;
                    if (j == 0)
                        firstColZero = true;
                    //the col j should be zeroed    
                    matrix[0][j] = 0;
                    matrix[i][0] = 0;
                }
            }
        }
        
        //begin from 1 because first row/col can be zero only if firstRowZero is true
        for(int i=1; i<matrix.size(); i++)
        {
            if (matrix[i][0] == 0)
            {
                for(int j =0; j<matrix[0].size(); j++)
                    matrix[i][j] = 0;
            }
        }

        for(int i=1; i<matrix[0].size(); i++)
        {
            if (matrix[0][i] == 0)
            {
                for(int j =0; j<matrix.size(); j++)
                    matrix[j][i] = 0;
            }
        }
        
        //zero first row if necessary
        if (firstRowZero)
        {
            for(int i =0; i<matrix[0].size(); i++)
                matrix[0][i] = 0;
        }

        if (firstColZero)
        {
            for(int i =0; i<matrix.size(); i++)
                matrix[i][0] = 0;
        }
    }

No comments:

Post a Comment