Leetcode 73. Set Matrix Zeroes

SnailTyan發表於2018-12-09

文章作者:Tyan
部落格:noahsnail.com  |  CSDN  |  簡書

1. Description

Set Matrix Zeroes

2. Solution

  • Version 1
class Solution {
public:
    void setZeroes(vector<vector<int>>& matrix) {
        int rows = matrix.size();
        if(rows == 0) {
            return;
        }
        int columns = matrix[0].size();
        vector<int> row;
        vector<int> 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<vector<int>>& 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/

相關文章