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?

题目大意:将矩阵中所有为0的单元所在的行,列均置为0;注意要区分是原本就是0,还是因为后来的置为0的。

最直观的解法是,新建立一个矩阵用来保存原矩阵中相应位置的值是否为0;这会耗费O(m*n)的空间;

改进方法是,矩阵为m*n,建立一个m大小的数组,用来保存每一行是否为0,n大小的数组用来保存每一列是否为0;耗费O(m + n)的空间。

继续改进,发现,可以用矩阵的第0行和第0列来保存上述的值,于是需要额外的row0和col0来保存第0行和第0列的原始状态。

class Solution {
public:
    void setZeroes(vector<vector<int>>& matrix) {
        bool row0 = false, col0 = false;

        int rows = matrix.size();
        int cols = matrix[0].size();
        for(int i = 0; i < cols; i++)
            if(matrix[0][i] == 0)
                row0 = true;

        for(int i = 0; i < rows; i++)
            if(matrix[i][0] == 0)
                col0 = true;

        for(int i = 1; i < rows; i++)
            for(int j = 1; j < cols; j++)
                if(matrix[i][j] == 0){
                    matrix[i][0] = 0;
                    matrix[0][j] = 0;
                }

        for (int i = 1; i < cols; ++i)
            if (matrix[0][i] == 0){
                for (int j = 1; j < rows; ++j) 
                    matrix[j][i] = 0;
            }
        for (int i = 1; i < rows; ++i)
            if (matrix[i][0] == 0){
                for (int j = 1; j < cols; ++j) 
                    matrix[i][j] = 0;
            }
        if (row0) for (int i = 0; i < cols; ++i) matrix[0][i] = 0;
        if (col0) for (int i = 0; i < rows; ++i) matrix[i][0] = 0;
    }
};

最优的解法:

void setZeroes(vector<vector<int> > &matrix) {
    int col0 = 1, rows = matrix.size(), cols = matrix[0].size();

    for (int i = 0; i < rows; i++) {
        if (matrix[i][0] == 0) col0 = 0;
        for (int j = 1; j < cols; j++)
            if (matrix[i][j] == 0)
                matrix[i][0] = matrix[0][j] = 0;
    }

    for (int i = rows - 1; i >= 0; i--) {
        for (int j = cols - 1; j >= 1; j--)
            if (matrix[i][0] == 0 || matrix[0][j] == 0)
                matrix[i][j] = 0;
        if (col0 == 0) matrix[i][0] = 0;
    }
}

对上述解法进行解释:首先将第0列是否有0存在保存在col0中,同样滴,将信息保存在第0列和第0行中,但是第0列为0何第0行为0均会使matrix[0][0]为0,所以需要一个col0来保存第0列是否为0,从而区分开来。最后将矩阵置0时,是从右下角开始的,不要从左上角开始。

results matching ""

    No results matching ""