-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathset-matrix-zeroes.rs
82 lines (71 loc) · 2.13 KB
/
set-matrix-zeroes.rs
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#![allow(dead_code, unused, unused_variables)]
fn main() {
let mut x = vec![vec![1, 1, 1], vec![1, 0, 1], vec![1, 1, 1]];
Solution::set_zeroes(&mut x);
}
struct Solution;
impl Solution {
/// 扫描。常规做法
pub fn set_zeroes1(matrix: &mut Vec<Vec<i32>>) {
let (mut v1, mut v2) = (vec![0; matrix.len()], vec![0; matrix[0].len()]);
for i in 0..matrix.len() {
for j in 0..matrix[0].len() {
if matrix[i][j] == 0 {
v1[i] = 1;
v2[j] = 1;
}
}
}
for i in 0..matrix.len() {
for j in 0..matrix[0].len() {
if v1[i] == 1 || v2[j] == 1 {
matrix[i][j] = 0;
}
}
}
}
/// 常规空间的做法
/// 标记做法:循环遍历每个元素,当元素为0时将这个元素对应的第一行的元素和第一列的元素都改为0
/// 然后从(1,1)开始遍历
/// 如果第一行或者第一列存在0,还要改变第一行和第一列
pub fn set_zeroes(matrix: &mut Vec<Vec<i32>>) {
let (mut row, mut column) = (false, false);
for i in 0..matrix.len() {
if matrix[i][0] == 0 {
column = true;
break;
}
}
for j in 0..matrix[0].len() {
if matrix[0][j] == 0 {
row = true;
break;
}
}
for i in 0..matrix.len() {
for j in 0..matrix[0].len() {
if matrix[i][j] == 0 {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
for i in 1..matrix.len() {
for j in 1..matrix[0].len() {
if matrix[i][0] == 0 || matrix[0][j] == 0 {
matrix[i][j] = 0;
}
}
}
if row {
for j in 0..matrix[0].len() {
matrix[0][j] = 0;
}
}
if column {
for i in 0..matrix.len() {
matrix[i][0] = 0;
}
}
}
}