Graphs Fewest steps with BFS
445. Shortest Path in Binary Matrix
You are given a square grid of integers, grid, with n rows and n columns. A cell that holds 0 is
open, and a cell that holds 1 is blocked.
A clear path starts at the top-left cell, (0, 0), and ends at the bottom-right cell, (n - 1, n - 1).
It visits only open cells. Each step moves to one of the eight cells around the current one: up, down,
left, right, or one of the four diagonals. The length of a path is the number of cells it visits,
counting the first and the last.
Return the length of the shortest clear path. If there is no clear path, return -1.
Example 1
Input: grid = [[0, 0, 0, 1, 0, 1],
[1, 0, 1, 1, 1, 0],
[0, 0, 1, 1, 0, 0],
[0, 1, 1, 0, 0, 1],
[0, 0, 0, 0, 0, 0],
[1, 1, 0, 1, 0, 0]]
9Explanation: The blocked cells in the middle push the path down the left side. One shortest path visits (0, 0), (1, 1), (2, 1), (3, 0), (4, 1), (4, 2), (4, 3), (4, 4) and (5, 5), which is 9 cells.
Example 2
Input: grid = [[0, 1, 0], [1, 1, 0], [0, 0, 0]]
-1Explanation: All three cells around the top-left cell are blocked, so no path can leave it.
Example 3
Input: grid = [[0]]
1Explanation: The top-left cell is also the bottom-right cell. The path is that one cell, so its length is 1.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
n == grid.length == grid[i].length1 ≤ n ≤ 300grid[i][j]is 0 or 1.
Clarifying questions
What you would ask an interviewer before writing any code.