You are given a 2D grid of integers where 0 is a passable cell and 1 is a wall, and a start cell located at one corner of the grid. Find the other corner of the grid that is closest to start by walking distance, and return its coordinates [row, col]. If no other corner is reachable, return [-1, -1].
Movement is allowed in 4 directions (up, down, left, right), and each step has a distance of 1. The four corners of the grid are (0, 0), (0, cols - 1), (rows - 1, 0) and (rows - 1, cols - 1).
Function Signature
def shortest_path_to_corner(grid: list[list[int]], start: list[int]) -> list[int]:
Rules
-
grid[r][c]
is
0
for a passable cell and
1
for a wall. A path never enters a wall and never leaves the grid.
-
start
is
[row, col]
of one of the four corners, and that cell is passable.
-
The targets are the three corners other than
start
. A target counts only if it is passable and reachable from
start
.
-
Return the target with the fewest steps. If several targets tie on distance, return the one with the smaller row, and if the rows are equal, the one with the smaller column.
-
If no target is reachable, return
[-1, -1]
.
Constraints
-
2 <= grid.length <= 200
-
2 <= grid[0].length <= 200
-
grid[i][j]
is
0
or
1
-
The starting corner cell is always passable (
0
)
-
At least one corner is passable
Examples
Input: grid = [[0,0,0],[0,1,0],[0,0,0]], start = [0,0]
Output: [0,2]
The other corners are (0,2), (2,0) and (2,2). Both (0,2) and (2,0) are 2 steps away and (2,2) is 4 steps away, so the tie goes to the smaller row, (0,2).
Input: grid = [[0,1,0],[0,1,0],[0,0,0]], start = [0,0]
Output: [2,0]
The wall in column 1 blocks the top row. Corner (2,0) is 2 steps down the left column, (2,2) is 4 steps away, and (0,2) takes 6 steps around the wall.
Input: grid = [[0,1],[1,0]], start = [1,1]
Output: [-1,-1]
Both neighbors of the start cell are walls, so the search cannot leave it. Corner (0,0) is passable but cut off, and the other two corners are walls.