Leetcode:73. Set Matrix Zeroes

Description

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

思路

  • 在原数组上面做,如果matrix[i][j] = 0, 由于第i行,第j列都要变成0,所以将matrix[i][0] = 0, matrix[0][j] = 0,这表明将该行该列所有元素置零
  • 特殊情况:第0行和第0列是特殊情况,单独考虑

代码

class Solution {
public:
    void setZeroes(vector<vector<int>>& matrix) {
        int m = matrix.size();
        if(m == 0) return;
        int n = matrix[0].size();
        
        int flag_m = 0, flag_n = 0;
        for(int i = 0; i < m; ++i){
            for(int j = 0; j < n; ++j){
                if(matrix[i][j] == 0){
                    if(i == 0) flag_m = 1;
                    if(j == 0) flag_n = 1;
                    matrix[i][0] = 0;
                    matrix[0][j] = 0;
                }
            }
        }
    
        int i = 1, j = 1;
        for(i = 1; i < m; ++i){
            for(j = 1; j < n; ++j){
                if(matrix[0][j] == 0 || matrix[i][0] == 0)
                    matrix[i][j] = 0;
            }
        }
        
        for(int i = 0; i < m; ++i){
            if(flag_n) 
                matrix[i][0] = 0;
        }
        
        for(int j = 0; j < n; ++j){
            if(flag_m)
                matrix[0][j] = 0;
        }
    }
};
posted @ 2017-05-31 19:33  JeffLai  阅读(116)  评论(0编辑  收藏  举报