Leetcode 73. Set Matrix Zeroes

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

1. Description

Set Matrix Zeroes

2. Solution

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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/
如果有收获,可以请我喝杯咖啡!