FastPrepMinimum Moves

Minimum Moves

Goldman Sachs logoGoldman Sachs● MediumINTERNOA
Learn

Problem statement

You are given an n x m grid maze. A value of 0 is an open cell and 1 is an obstacle. Start at (0, 0) and reach (n - 1, m - 1).

In one move, choose one of the four cardinal directions and a distance from 1 through k. The destination must remain inside the grid, and every crossed cell, including the destination, must be open. You may not jump over an obstacle.

Return the minimum number of moves needed, or -1 when the destination is unreachable.

Function

getMinimumMoves(maze: int[][], k: int) → int

Examples

Example 1

maze = [[0, 0], [1, 0]]k = 2return = 2

Move from (0,0) to (0,1), then to (1,1). The destination cannot be reached in one cardinal move, so the minimum is 2.

Example 2

maze = [[0, 0, 0], [1, 0, 0], [1, 0, 0]]k = 5return = 2

Jump from (0,0) to (0,2), then down to (2,2). Both jumps stay on open cells, so the minimum is 2.

Example 3

maze = [[0, 1, 0], [1, 0, 0], [1, 0, 0]]k = 5return = -1

The cells immediately right of and below (0,0) are obstacles. Because a jump cannot cross an obstacle, no move can begin and the answer is -1.

Constraints

  • 1 <= n, m <= 100
  • 1 <= k <= 100
  • Every cell is either 0 or 1.

More Goldman Sachs problems

See Goldman Sachs hiring insights
public int getMinimumMoves(int[][] maze, int k) {
  // write your code here
}
maze[[0, 0], [1, 0]]
k2
expected2
Checking account…