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
|
fn main() {
let tests: Vec<Vec<Vec<i32>>> = vec![
vec![
vec![2,1,1],
vec![1,1,0],
vec![0,1,1]
],
vec![
vec![2,1,1],
vec![0,1,1],
vec![1,0,1]
],
vec![
vec![0,2]
],
vec![
vec![1,2]
]
];
let outputs = [4,-1,0,1];
for (n, test) in tests.iter().enumerate() {
let c: Vec<Vec<i32>> = test.to_vec();
let result = oranges_rotting(c);
println!("test {} result {} should be {}", n, result, outputs[n]);
}
}
fn oranges_rotting(grid: Vec<Vec<i32>>) -> i32 {
let mut grid1 = grid.clone();
let mut grid2 = grid1.clone();
let mut minutes: i32 = -1;
let mut some_fresh: bool = true;
let mut some_different: bool;
while some_fresh {
some_fresh = false;
some_different = false;
println!("Minute {}", minutes);
for (x, row) in grid1.iter().enumerate() {
for (y, col) in row.iter().enumerate() {
some_fresh |= *col == 1;
if *col != 2 {continue;}
let r: [i32; 3] = [-1,0,1];
for ix in r {
for iy in r {
if ix.abs() == iy.abs() {continue;}
let field: &mut i32 = &mut grid2[
(x as i32 + ix).clamp(0,grid.len() as i32 -1) as usize
][
(y as i32 + iy).clamp(0,grid[0].len() as i32 -1) as usize
];
if *field == 1 {
*field = 2;
}
}
}
}
println!("{:?} {:?}", row, grid2[x]);
}
for (x, row) in grid1.iter().enumerate() {
for (y, col) in row.iter().enumerate() {
some_different |= grid1[x][y] != grid2[x][y];
}
}
if !some_different && some_fresh {
println!("impossible");
return -1;
}
grid1 = grid2;
grid2 = grid1.clone();
minutes += 1;
}
return minutes;
}
|