FastPrepShortest Path Between Grid Points

Shortest Path Between Grid Points

Bloomberg LP logoBloomberg LP● MediumNEW GRADONSITE INTERVIEW
Learn

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) → int

Examples

Example 1

grid = [[0,0,0],[1,1,0],[0,0,0]]startRow = 0startCol = 0targetRow = 2targetCol = 2return = 4

Move 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 = -1

Both possible first moves are blocked.

Example 3

grid = [[0]]startRow = 0startCol = 0targetRow = 0targetCol = 0return = 0

The 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 0 or 1.
  • The start and target coordinates are inside the grid and refer to open cells.
  • The total number of cells is at most 250000.

More Bloomberg LP problems

See Bloomberg LP hiring insights
public int shortestGridPath(int[][] grid, int startRow, int startCol, int targetRow, int targetCol) {
    // Write your code here.
}
grid[[0,0,0],[1,1,0],[0,0,0]]
startRow0
startCol0
targetRow2
targetCol2
expected4
Checking account…