Leetcode Set Matrix Zeroes

OpenSoucre發表於2014-06-26

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;
    }
};

 

相關文章