Shortest Path Between Grid Points
Problem statement
Given a rectangular binary matrix grid and two open cells (startRow, startCol) and (targetRow, targetCol), return the minimum number of moves needed to reach the target from the start.
From an open cell, you may move one cell up, down, left, or right. A cell containing 0 is open and a cell containing 1 is blocked. You may not enter blocked cells. Return -1 if the target is unreachable.
Function
shortestGridPath(grid: int[][], startRow: int, startCol: int, targetRow: int, targetCol: int) → intExamples
Example 1
grid = [[0,0,0],[1,1,0],[0,0,0]]startRow = 0startCol = 0targetRow = 2targetCol = 2return = 4Move right twice and then down twice. The blocked middle-row cells prevent a shorter route.
Example 2
grid = [[0,1],[1,0]]startRow = 0startCol = 0targetRow = 1targetCol = 1return = -1Both possible first moves are blocked.
Example 3
grid = [[0]]startRow = 0startCol = 0targetRow = 0targetCol = 0return = 0The start is already the target, so no move is needed.
Constraints
1 <= grid.length, grid[0].length <= 500- Every row has the same length, and every cell is
0or1. - The start and target coordinates are inside the grid and refer to open cells.
- The total number of cells is at most
250000.