leetcode Set Matrix Zeroes

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.

click to show follow up.

Follow up:

Did you use extra space?
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?

题中要求额外空间尽可能小,自己能想到最小额外空间也有m+n,用来记录哪一行、哪一列设为0

参考别人思路,可以不用多余的额外空间。具体思路就是使用原矩阵第0行,第0列来记录哪一行、哪一列设为0,代码思路如下:

class Solution {
public:
    void setZeroes(vector<vector<int> >& matrix) {
        if(matrix.empty() || matrix.empty())
        return;
    int row = matrix.size();
        int sol = matrix[0].size();
        int i, j;
        bool rowflag = false;
        bool solflag = false;
        //记录第0行、第0列中是否原来有0
        for(j=0; j<sol; ++j) if(matrix[0][j]==0) solflag = true;
        for(i=0; i<row; ++i) if(matrix[i][0]==0) rowflag = true;
        //非第0行、第0列中元素为0,设置为该0元素对应的第0行、第0列为0,以用第0行、第0列来记录哪一列、哪一行中要设置为零
        for(i=1; i<row; ++i)
        {
        for(j=1; j<sol; ++j)
        {
        if(matrix[i][j]==0)
        {
        matrix[i][0] = 0;
        matrix[0][j] = 0;
        }
        }
        }
        //从1开始,因为要用第0行、第0列来记录哪一列、哪一行中要设置为零
        for(i=1; i<row; ++i)
        if(matrix[i][0] == 0)
        for(j=1; j<sol; ++j)
        matrix[i][j] = 0;


        for(j=1; j<sol; ++j)
        if(matrix[0][j] == 0)
        for(i=1; i<row; ++i)
        matrix[i][j] = 0;
        //如果第0行、第0列中原来是否有0
        if(solflag)
        for(j=0; j<sol;++j)
        matrix[0][j] = 0;
        if(rowflag)
        for(i=0; i<row; ++i)
        matrix[i][0] = 0;
    }
};
点赞