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.

思路:完全的in-place,利用了第一次出现0位置的第i行和第j列存储将来可能出现0的行的下标和列的下标

class Solution {
public:
    void setZeroes(vector<vector<int> > &matrix) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int zero_row = 0, zero_col = 0;
        int row_iter = 0, col_iter = 0;
        bool first = false;
        for(int i = 0; i < matrix.size(); i++){
            for(int j = 0; j < matrix[0].size();j++){
                if (matrix[i][j] == 0){
                    if (!first){
                        zero_row = i;
                        zero_col = j;
                        //zero_row和zero_col都清空,并且后续都不访问这一行和这一列
                        for(int k = 0; k < matrix[0].size(); k++){
                            if (matrix[zero_row][k] == 0){
                                matrix[zero_row][k] = k+1;
                            }else{
                                matrix[zero_row][k] = 0;
                            }
                        }
                        for(int k = 0; k < matrix.size(); k++){
                            if (matrix[k][zero_col] == 0){
                                matrix[k][zero_col] = k+1;
                            }else{
                                matrix[k][zero_col] = 0;
                            }
                        }
                        first = true;
                    }else if (i != zero_row && j != zero_col){
                        matrix[zero_row][j] = j + 1;
                        matrix[i][zero_col] = i + 1;
                    }
                }
            }
        }
        if (!first){
            return;
        }
        //对应的行给0 去掉zero_row行
        for(int i = 0; i < matrix.size();i++){
            if (i != zero_row && matrix[i][zero_col]){
                for(int j = 0; j < matrix[0].size(); j++){
                    matrix[i][j] = 0;
                }
            }
        }
        //对应的列给0 去掉zero_col对应的列
        for(int j = 0; j < matrix[0].size();j++){
            if (j != zero_col && matrix[zero_row][j]){
                for(int i = 0; i < matrix.size(); i++){
                    matrix[i][j] = 0;
                }
            }
        }
        //zero_row和zero_col给0
        for(int k = 0; k < matrix[0].size(); k++){
                matrix[zero_row][k] = 0;
        }
        for(int k = 0; k < matrix.size(); k++){
                matrix[k][zero_col] = 0;
        }        
    }
};

 

posted @ 2013-07-10 21:18  一只会思考的猪  阅读(187)  评论(0编辑  收藏  举报