Skip to content

Commit 0a061a3

Browse files
committed
7-27-2020
1 parent 43232bd commit 0a061a3

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed

src/_0994_rotting_oranges.rs

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
struct Solution;
2+
impl Solution {
3+
pub fn oranges_rotting(mut grid: Vec<Vec<i32>>) -> i32 {
4+
let n: usize = grid.len();
5+
let m: usize = grid[0].len();
6+
let mut h_rotting: Vec<(usize, usize)> = vec![];
7+
let mut fresh_count: bool = false;
8+
let mut result: i32 = -1;
9+
10+
for i in 0..n {
11+
for j in 0..m {
12+
if grid[i][j] == 2 {
13+
h_rotting.push((i, j));
14+
} else if grid[i][j] == 1 {
15+
fresh_count = true;
16+
}
17+
}
18+
}
19+
if !fresh_count {
20+
return 0;
21+
}
22+
23+
while !h_rotting.is_empty() {
24+
result += 1;
25+
let mut h_rotting_temp: Vec<(usize, usize)> = vec![];
26+
27+
while let Some(orange) = h_rotting.pop() {
28+
if orange.0 > 0 && grid[orange.0 - 1][orange.1] == 1 {
29+
h_rotting_temp.push((orange.0 - 1, orange.1));
30+
grid[orange.0 - 1][orange.1] = 2;
31+
}
32+
if orange.0 < n - 1 && grid[orange.0 + 1][orange.1] == 1 {
33+
h_rotting_temp.push((orange.0 + 1, orange.1));
34+
grid[orange.0 + 1][orange.1] = 2;
35+
}
36+
if orange.1 > 0 && grid[orange.0][orange.1 - 1] == 1 {
37+
h_rotting_temp.push((orange.0, orange.1 - 1));
38+
grid[orange.0][orange.1 - 1] = 2;
39+
}
40+
if orange.1 < m - 1 && grid[orange.0][orange.1 + 1] == 1 {
41+
h_rotting_temp.push((orange.0, orange.1 + 1));
42+
grid[orange.0][orange.1 + 1] = 2;
43+
}
44+
}
45+
h_rotting = h_rotting_temp;
46+
}
47+
48+
for i in 0..grid.len() {
49+
for j in 0..grid[0].len() {
50+
if grid[i][j] == 1 {
51+
return -1;
52+
}
53+
}
54+
}
55+
56+
result
57+
}
58+
}
59+
60+
#[test]
61+
fn test() {
62+
assert_eq!(
63+
Solution::oranges_rotting(vec_vec_i32![[2, 1, 1], [1, 1, 0], [0, 1, 1]]),
64+
4
65+
);
66+
assert_eq!(
67+
Solution::oranges_rotting(vec_vec_i32![[2, 1, 1], [0, 1, 1], [1, 0, 1]]),
68+
-1
69+
);
70+
assert_eq!(Solution::oranges_rotting(vec_vec_i32![[0, 2]]), 0);
71+
}

src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,8 @@ mod _0953_verifying_an_alien_dictionary;
152152
//
153153
mod _0977_squares_of_a_sorted_array;
154154
//
155+
mod _0994_rotting_oranges;
156+
//
155157
mod _1013_partition_array_into_three_parts_with_equal_sum;
156158
//
157159
mod _1021_remove_outermost_parentheses;

0 commit comments

Comments
 (0)