FastPrepShortest Path in a Blocked Grid

Shortest Path in a Blocked Grid

Spotify logoSpotify● MediumFULLTIMEPHONE SCREEN

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

Examples

Example 1

grid = [[0,0,0],[1,1,0],[0,0,0]]start = [0,0]target = [2,0]return = 6

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

Every 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 = 0

start and target are the same cell, so no move is needed.

Constraints

  • 1 <= grid.length <= 100
  • 1 <= grid[i].length <= 100
  • All rows have the same length.
  • 0 <= grid[i][j] <= 1
  • start.length == 2
  • target.length == 2
  • start and target are cells inside the grid, and both cells hold 0.

More Spotify problems

See Spotify hiring insights
Saved
public int shortestPath(int[][] grid, int[] start, int[] target) {
    // Write your code here.
}
Checking account…