Given a 2D grid of size m x n, where 0 represents a walkable cell and 1 represents an obstacle, find the shortest path from the top-left corner (0, 0) to the bottom-right corner (m-1, n-1).
You must implement the A* pathfinding algorithm. You can move in 4 directions: up, down, left and right. Each move has a cost of 1.
Return the length of the shortest path, counted as the number of cells visited including the start and the end. If no path exists, return -1.
Function Signature
def shortest_path(grid: list[list[int]]) -> int:
Rules
-
grid[r][c]
is the cell in row
r
and column
c
. Row 0 is the top row.
-
A path may only pass through cells with value
0
and may not leave the grid.
-
The length counts cells, so a path with
k
moves has length
k + 1
. A 1 x 1 grid has a path of length 1.
Constraints
-
1 <= m, n <= 200
-
grid[i][j]
is
0
or
1
-
grid[0][0] == 0
-
grid[m-1][n-1] == 0
Examples
Input: grid = [[0,0,0],
[1,1,0],
[0,0,0]]
Output: 5
The only open cell in the middle row is on the right, so the path is (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2), which visits 5 cells.
Input: grid = [[0,1],
[1,0]]
Output: -1
Both neighbors of (0,0) are obstacles, so no path exists.
Input: grid = [[0,1,0,0,0],
[0,1,0,1,0],
[0,0,0,1,0]]
Output: 11
The walls force a detour: down the left column, right along the bottom row to (2,2), up to (0,2), right to (0,4) and down to (2,4). That is 10 moves and 11 cells, although the goal would be only 6 moves away on an empty grid.