You are given a 2D game map as an m x n grid of integers grid. Each cell holds one of two values:
-
0
: an empty walkable tile
-
1
: a wall (impassable)
A player starts at the top-left cell (0, 0) and wants to reach the bottom-right cell (m - 1, n - 1). From any cell, the player can move one step in any of the four cardinal directions (up, down, left, right) as long as the destination cell is within the grid and is not a wall.
Return the length of the shortest path, measured in steps, from the start to the destination. If no such path exists, or if either the start or the destination cell is a wall, return -1.
Function Signature
def shortest_path(grid: list[list[int]]) -> int:
...
Rules
-
The length of a path is the number of moves it makes. A path that visits k cells has length k - 1, so a map that is a single open cell has answer
0
.
-
Only up, down, left and right moves are allowed. Diagonal moves are not.
-
Return
-1
when the start is a wall, when the destination is a wall, or when the walls separate the two.
Constraints
-
m == grid.length
-
n == grid[i].length
-
1 <= m, n <= 500
-
grid[i][j]
is either
0
or
1
.
Examples
Input: grid = [[0,0,0],
[1,1,0],
[0,0,0],
[0,1,1],
[0,0,0]]
Output: 10
Row 1 is open only at column 2 and row 3 is open only at column 0, so every path passes through (1, 2) and (3, 0). Reaching (1, 2) takes 3 moves, going from there along row 2 to (3, 0) takes 4, and going down to (4, 0) and right to (4, 2) takes 3 more, for 10 in total.
Input: grid = [[0,1],[1,0]]
Output: -1
Both neighbors of the start, (0, 1) and (1, 0), are walls, so the player cannot leave (0, 0) and the destination is unreachable.
Input: grid = [[0]]
Output: 0
The start is already the destination, so the shortest path makes no moves.