C++ O(1) space, O(m*n) time - use the first row / col for storing the zero info, then handle them separately


  • 0
    X
    void setZeroes(vector<vector<int>>& matrix) {
        if(matrix.empty() || matrix[0].empty())
        {
            return;
        }
        
        bool zeroFirstRow = false, zeroFirstCol = false;
        for(auto i = 0; i < matrix.size(); ++i)
        {
            if(matrix[i][0] == 0)
            {
                zeroFirstCol = true;
                break;
            }
        }
        for(auto i = 0; i < matrix[0].size(); ++i)
        {
            if(matrix[0][i] == 0)
            {
                zeroFirstRow = true;
                break;
            }
        }        
        for(auto i = 1; i < matrix.size(); ++i)
        {
            for(auto j = 1; j < matrix[i].size(); ++j)
            {
                if(matrix[i][j] == 0)
                {
                    matrix[i][0] = 0;
                    matrix[0][j] = 0;
                }
            }
        }
        
        for(auto i = 1; i < matrix.size(); ++i)
        {
            if(matrix[i][0] == 0)
            {
                matrix[i].assign(matrix[i].size(), 0);
            }
        }
        
        for(auto i = 1; i < matrix[0].size(); ++i)
        {
            if(matrix[0][i] == 0)
            {
                for(auto j = 1; j < matrix.size(); ++j)
                {
                    matrix[j][i] = 0;
                }
            }
        }
        if(zeroFirstRow)
        {
            matrix[0].assign(matrix[0].size(), 0);
        }
        if(zeroFirstCol)
        {
            for(auto i = 0; i < matrix.size(); ++i)
            {
                matrix[i][0] = 0;
            }
        }

Log in to reply
 

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