description

Given an n x n binary matrix grid, return the length of the shortest clear path in the matrix. If there is no clear path, return -1.

A clear path in a binary matrix is a path from the top-left cell (i.e., (0, 0)) to the bottom-right cell (i.e., (n - 1, n - 1)) such that:

  • All the visited cells of the path are 0.
  • All the adjacent cells of the path are 8-directionally connected (i.e., they are different and they share an edge or a corner).

The length of a clear path is the number of visited cells of this path.

 

Example 1:

Input: grid = [[0,1],[1,0]]
Output: 2

Example 2:

Input: grid = [[0,0,0],[1,1,0],[1,1,0]]
Output: 4

Example 3:

Input: grid = [[1,0,0],[1,1,0],[1,1,0]]
Output: -1

 

Constraints:

  • n == grid.length
  • n == grid[i].length
  • 1 <= n <= 100
  • grid[i][j] is 0 or 1

submission

// BFS with double queue
impl Solution {
    pub fn shortest_path_binary_matrix(mut grid: Vec<Vec<i32>>) -> i32 {
        // 8 directions
        #[rustfmt::skip]
        let dirs = [[0, 1], [1, 1], [1, 0], [1, -1], [0, -1], [-1, -1], [-1, 0], [-1, 1]];
        let n = grid.len() as i32;
        // double "queue"
        let (mut queue, mut swp) = (vec![], vec![]);
        let mut steps = 0;
        queue.push((0i32, 0i32));
        // helper lambda to check range
        let inrange = |x: i32, y: i32| x >= 0 && x < n && y >= 0 && y < n;
        while !queue.is_empty() {
            // keep track of steps
            steps += 1;
            while let Some((x, y)) = queue.pop() {
                // check range and value and mark visited
                if !inrange(x, y) || std::mem::replace(&mut grid[x as usize][y as usize], 1) != 0 {
                    continue;
                }
                // reach destination, return
                if x == n - 1 && y == n - 1 {
                    return steps;
                }
                // push adjacent cells to another queue
                for [dx, dy] in dirs {
                    swp.push((x + dx, y + dy));
                }
            }
            // alternate between two queues
            std::mem::swap(&mut queue, &mut swp);
        }
        // unreachable
        -1
    }
}