A tricky solution, and I wonder can this satisfy the "const place"?


  • 0
    R
    class Solution {
    public:
        void setZeroes(vector<vector<int> > &matrix) {
            int m = matrix.size();
            int n = matrix[0].size();
            
            bool line = false;
            bool hine = false;
            
            for (int i=0;i!=m;i++)
                for (int j=0;j!=n;j++)
                    if (matrix[i][j] == 0) {
                        matrix[0][j] = 0;
                        matrix[i][0] = 0;
                        if (i == 0)
                            line = true;
                        if (j == 0)
                            hine = true;
                    }
            for (int i=m-1;i!=0;i--)
                if (matrix[i][0] == 0){
                    for(int j=0;j!=n;j++)
                        matrix[i][j] = 0;
                }
            
            for(int j=n-1;j!=0;j--)
                if (matrix[0][j] == 0)
                    for(int k=0;k!=m;k++)
                        matrix[k][j] = 0;
            if (matrix[0][0] == 0){
                if (hine)
                    for (int i=0;i!=m;i++)
                        matrix[i][0] = 0;
                if (line)
                    for (int j=0;j!=n;j++)
                        matrix[0][j] = 0;
            }
            
            
        }
    };

  • 0
    S
    This post is deleted!

  • 0
    S

    Thanks for your post. However it would be better to share solution with correct code format and elaborated thoughts. Please read the Discuss FAQ for more info. Take a look at good sharing example


  • 0
    S

    This code only uses several variables. It should be considered as const space and in place.


  • 0
    F

    I don't see why you need to check if matrix[0][0] == 0 before setting the first row and first column. My code w/o the check got passed. Could you explain me about it?


  • 0
    R

    Hi, if matrix[0][0] is set to 0. It may caused by one 0 in the first col, or by one 0 in the first row, or both. So i use line and hine to distinguish the two situations.


  • 0
    F

    Actually both first row and first column are not set till the end. If matrix[0][0] == 0, we don't need to check it because first row and first column should be set to 0, and hine and line are always true. If matrix[0][0] == 1, we need help from the booleans. So we can cancel the if block and just check whether hine or line is true.


Log in to reply
 

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