Sharing my 84ms in-place C++ solution


  • 0
    T
    class Solution {
    public:
        void setZeroes(vector<vector<int>>& matrix) {
            int m = matrix.size();
            if(m==0)
                return;
            int n = matrix[0].size();
            if(n==0)
                return;
                
            bool firstRowHasZero = false;
            bool firstColumnHasZero = false;
            int i, j;
            for(i=0; i<m; i++)
                if(matrix[i][0]==0)
                {
                    firstColumnHasZero = true;
                    break;
                }
                
            for(j=0; j<n; j++)
                if(matrix[0][j]==0)
                {
                    firstRowHasZero = true;
                    break;
                }
                
            for(i=1; i<m; i++)
                for(j=1; j<n; j++)
                {
                    if(matrix[i][j]==0)
                    {
                        matrix[i][0] = 0;
                        matrix[0][j] = 0;
                    }
                }
                
            for(i=1; i<m; i++)
            {
                if(matrix[i][0]==0)
                {
                    for(j=1; j<n; j++)
                        matrix[i][j] = 0;
                }
            }
            
            for(j=1; j<n; j++)
            {
                if(matrix[0][j] == 0)
                {
                    for(i=1; i<m; i++)
                        matrix[i][j] = 0;
                }
            }
            
            if(firstRowHasZero)
            {
                for(j=0; j<n; j++)
                    matrix[0][j]=0;
            }
            
            if(firstColumnHasZero)
            {
                for(i=0; i<m; 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.