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?

 由于题目要求用常量空间,故要利用matrix本身的空间

本题将第1行和第1列作为重用空间

首先寻找第1行和第1列是否含有0,如果含有0,标记下来,到最后再将第1行和第1列置为0

现在遍历matrix其他元素,如果含有0,则将该行的第1个元素置为0, 将该列的第1个元素置为0,

遍历完后,根据第一行和第1列将含有0的行和列置为0 即可

class Solution {
public:
    void setZeroes(vector<vector<int> > &matrix) {
        int n = matrix.size(), m = matrix[0].size();
        bool rowZero = false, colZero = false;
        for(int i = 0 ; i < m; ++ i) if(!matrix[0][i]) rowZero = true;
        for(int i = 0 ; i < n; ++ i) if(!matrix[i][0]) colZero = true;
        for(int i = 1 ; i < n; ++ i){
            for(int j = 1 ; j < m; ++ j){
                if(!matrix[i][j]) {matrix[0][j]=0;matrix[i][0]=0;}
            }
        }
        for(int i =1; i < n ; ++ i){
            for(int j  =1; j < m; ++ j){
                if(!matrix[0][j] || !matrix[i][0]) matrix[i][j] = 0;
            }
        }
        if(rowZero) for(int i = 0 ; i < m; ++ i) matrix[0][i] = 0;
        if(colZero) for(int i = 0 ; i < n; ++ i) matrix[i][0] = 0;
    }
};

 

posted @ 2014-06-26 22:55  OpenSoucre  阅读(183)  评论(0编辑  收藏  举报