-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.rs
33 lines (33 loc) · 1.04 KB
/
Solution.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
use std::collections::VecDeque;
impl Solution {
pub fn shortest_path_binary_matrix(mut grid: Vec<Vec<i32>>) -> i32 {
let n = grid.len();
let mut queue = VecDeque::new();
queue.push_back([0, 0]);
let mut res = 0;
while !queue.is_empty() {
res += 1;
for _ in 0..queue.len() {
let [i, j] = queue.pop_front().unwrap();
if grid[i][j] == 1 {
continue;
}
if i == n - 1 && j == n - 1 {
return res;
}
grid[i][j] = 1;
for x in -1..=1 {
for y in -1..=1 {
let x = x + i as i32;
let y = y + j as i32;
if x < 0 || x == n as i32 || y < 0 || y == n as i32 {
continue;
}
queue.push_back([x as usize, y as usize]);
}
}
}
}
-1
}
}