Shortest Path in Binary Matrix
MediumP2Coding
Given an n x n binary grid, find the length of the shortest clear path from the top-left cell (0, 0) to the bottom-right cell (n - 1, n - 1). A clear path visits only cells containing 0 and each step moves to one of the 8 neighbouring cells (including diagonals). The length is the number of cells on the path, both ends included. Return -1 if no clear path exists.
Example 1
- Input
- grid = [[0,1],[1,0]]
- Output
- 2
- Why
- Move diagonally from (0,0) to (1,1).
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
- Why
- The start cell is blocked.
Constraints
- 1 <= n <= 100
- grid[i][j] is 0 or 1
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 9. ⌘Enter runs, ⌘⇧Enter submits.