Shortest Path in a Blocked Grid
Problem statement
You are given a grid of 0 and 1 values. A 0 is an open cell and a 1 is blocked. You are also given start and target, each written as [row, column].
Starting at start, you may move one cell at a time up, down, left or right, and you may never step on a blocked cell or leave the grid.
Return the fewest moves needed to reach target. If you cannot reach it, return -1. If start and target are the same cell, the answer is 0.
Function
shortestPath(grid: int[][], start: int[], target: int[]) → intExamples
Example 1
grid = [[0,0,0],[1,1,0],[0,0,0]]start = [0,0]target = [2,0]return = 6The blocked cells in row 1 force the walk to go around the right side: (0,0), (0,1), (0,2), (1,2), (2,2), (2,1), (2,0). That is 6 moves.
Example 2
grid = [[0,1],[1,0]]start = [0,0]target = [1,1]return = -1Every neighbor of both end cells is blocked, and diagonal moves are not allowed, so the target cannot be reached.
Example 3
grid = [[0,0],[0,0]]start = [1,0]target = [1,0]return = 0start and target are the same cell, so no move is needed.
Constraints
1 <= grid.length <= 1001 <= grid[i].length <= 100- All rows have the same length.
0 <= grid[i][j] <= 1start.length == 2target.length == 2startandtargetare cells inside the grid, and both cells hold0.