|
| 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 | +} |
0 commit comments