c++ O(1) space solution


  • 0
    void setZeroes(vector<vector<int>>& matrix) 
    {
        bool frzero = false;
        bool fczero = false;
        for (int i = 0; i < matrix.size(); i++)
        {
            for (int j = 0; j < matrix[0].size(); j++)
            {
                if (matrix[i][j] == 0)
                {
                    if (i == 0)
                        frzero = true;
                    if (j == 0)
                        fczero = true;
                    matrix[i][0] = 0;
                    matrix[0][j] = 0;
                }
            }
        }
        
        for (int i = 1; i < matrix.size(); i++)
        {
            for (int j = 1; j < matrix[0].size(); j++)
            {
                if ((matrix[i][0] == 0) || (matrix[0][j] == 0)) 
                {
                    matrix[i][j] = 0;
                }
            }
        }
        if (frzero)
        {
            for (int j = 0; j < matrix[0].size(); j++)
                matrix[0][j] = 0;
        }
        if (fczero)
        {
            for (int 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.