My c++ solution with O(1) space


  • -5
    R
    void setZeroes(int **matrix, int m, int n) {
        int i,j,k;
        for(i=0;i<m;i++)
        {
            for(j=0;j<n;j++)
            {
                if(matrix[i][j]==0)
                {
                    for(k=0;k<n;k++)
                    {   if(matrix[i][k])                       // if cell has no zero element
                        matrix[i][k]=-99;  // set  column with -99
                    }
                    for(k=0;k<m;k++)
                    {   if(matrix[k][j])
                        matrix[k][j]=-99;  //set  row with -99
                    }
                }
            }
        }
        for(i=0;i<m;i++)
        {
            for(j=0;j<n;j++)
            {
                if(matrix[i][j]==-99)
                {
                    matrix[i][j]=0;        // at last set each cell with -99 to 0
                }
            }
        }
    }

  • 0
    L

    It is a good approach, but it is wrong, because the elements in the matrix can be -99.


  • 0
    R

    you can set it to minimum possible value using INT_MIN .
    It is just an example to use -99


  • 0
    H

    Actually the value in the matrix can be INT_MIN too.


Log in to reply
 

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