Safest Shortest Path Through a Grid
Problem statement
You are given a rectangular binary grid and two open cells, start and target. A 0 is an open cell and a 1 is a blocked cell. Coordinates use [row,column] with zero-based indices.
For this exercise, move one cell up, down, left, or right through open cells. Each move costs one step. Blocked cells cannot be entered.
Choose the route
- First, minimize the number of moves from
starttotarget. - Among routes with that minimum number of moves, maximize their clearance from blocked cells.
A cell's clearance is its minimum Manhattan distance to any blocked cell. The Manhattan distance from (r,c) to (x,y) is |r-x| + |c-y|; it is measured directly, without routing around obstacles. A route's clearance is the smallest cell clearance along the route, including both endpoints.
Return [moves,clearance] for the chosen route. Return [-1,-1] if no route exists. If the grid has no blocked cells, use -1 for clearance because there is no obstacle to measure from. If start == target, the route has 0 moves and includes that one cell.
Function
safestShortestPath(grid: int[][], start: int[], target: int[]) → int[]Examples
Example 1
grid = [[0,0,0,0,0],[0,0,0,0,0],[0,0,1,0,0],[0,0,0,0,0],[0,0,0,0,0]]start = [0,0]target = [4,4]return = [8,2]A route along the top row and right edge uses 8 moves and stays at least 2 cells from the blocked center. Every route needs at least 8 moves, and no shortest route can keep a larger clearance.
Example 2
grid = [[0,0,0,0,0],[0,0,0,0,0],[0,0,1,0,0],[0,0,0,0,0],[0,0,0,0,0]]start = [2,0]target = [2,4]return = [6,1]The blocked center forces a detour. A shortest route uses 6 moves and passes next to the obstacle, so its clearance is 1. A route with clearance 2 would need 8 moves and loses because fewer moves come first.
Example 3
grid = [[0,1],[1,0]]start = [0,0]target = [1,1]return = [-1,-1]Both neighbors of the start are blocked, so the target cannot be reached. Return [-1,-1].
Constraints
1 <= grid.length <= 80.1 <= grid[0].length <= 80.- Every row has the same length, and every entry is
0or1. start.length == target.length == 2.- Both coordinates are inside the grid and name open cells.