LeetCode 1091. Shortest Path in Binary Matrix

Problem Statement



use std::collections::VecDeque;

impl Solution {
pub fn shortest_path_binary_matrix(grid: Vec<Vec<i32>>) -> i32 {
let mut g = grid.clone();
let n = g.len();
if n == 0 {
return -1;
}
if g[0][0] == 1 || g[n - 1][n - 1] == 1 {
return -1;
}
if n == 1 {
return 1;
}

let mut q = VecDeque::new();
q.push_back((0, 0));
let (dx, dy) : ([i32; 8], [i32; 8]) = ([1, -1, 0, 0, 1, 1, -1, -1],
[0, 0, 1, -1, 1, -1, 1, -1]);
let mut level = 1;
while !q.is_empty() {
let size = q.len();
level += 1;
for _i in 0..size {
let cur = q.front().unwrap().clone(); q.pop_front();
let (x, y) = (cur.0, cur.1);
for j in 0..8 {
let (xx, yy) = (x + dx[j], y + dy[j]);
if xx < 0 || yy < 0 || xx as usize >= n || yy as usize >= n {
continue;
}
let (nx, ny) = (xx as usize, yy as usize);
if nx == n - 1 && ny == n - 1 {
return level;
}
if g[nx][ny] == 1 {
continue;
}
g[nx][ny] = 1;
q.push_back((nx as i32, ny as i32));
}
}
}
return -1;
}
}