Leetcode 73. Set Matrix Zeroes

文章作者:Tyan
博客:noahsnail.com  |  CSDN  | 

1. Description

Leetcode 73. Set Matrix Zeroes_第1张图片
Set Matrix Zeroes

2. Solution

  • Version 1
class Solution {
public:
    void setZeroes(vector>& matrix) {
        int rows = matrix.size();
        if(rows == 0) {
            return;
        }
        int columns = matrix[0].size();
        vector row;
        vector column;
        for(int i = 0; i < rows; i++) {
            for(int j = 0; j < columns; j++) {
                if(!matrix[i][j]) {
                    row.push_back(i);
                    column.push_back(j);
                }
            }
        }
        for(int i = 0; i < row.size(); i++) {
            for(int j = 0; j < columns; j++) {
                matrix[row[i]][j] = 0;
            }
        }
        for(int j = 0; j < column.size(); j++) {
            for(int i = 0; i < rows; i++) {
                matrix[i][column[j]] = 0;
            }
        }
    }
};
  • Version 2
class Solution {
public:
    void setZeroes(vector>& matrix) {
        int rows = matrix.size();
        if(rows == 0) {
            return;
        }
        int columns = matrix[0].size();
        bool row = false;
        bool column = false;
        for(int i = 0; i < rows; i++) {
            for(int j = 0; j < columns; j++) {
                if(!matrix[i][j]) {
                    if(!i) {
                        row = true;
                    }
                    if(!j) {
                        column = true;
                    }
                    matrix[0][j] = 0;
                    matrix[i][0] = 0;
                }
            }
        }
        for(int i = 1; i < rows; i++) {
            for(int j = 1; j < columns; j++) {
                if(!matrix[0][j] || !matrix[i][0]) {
                    matrix[i][j] = 0;
                }
            }
        }
        if(row) {
            for(int j = 0; j < columns; j++) {
                matrix[0][j] = 0;
            } 
        }
        if(column) {
            for(int i = 0; i < rows; i++) {
                matrix[i][0] = 0;
            }
        }
    }
};

Reference

  1. https://leetcode.com/problems/set-matrix-zeroes/description/

你可能感兴趣的:(Leetcode 73. Set Matrix Zeroes)