FastPrepMinimum Moves

Minimum Moves

Harness logoHarness● MediumFULLTIMEOA
Learn

Problem statement

You are given an n x m grid maze. A cell containing 0 is open, and a cell containing 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 be inside the grid, and every cell crossed, including the destination, must be open. You cannot jump over an obstacle.

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

For this exercise, assume a blocked starting or destination cell makes the journey impossible. If the grid consists of one open cell, return 0.

Function

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

Examples

Example 1

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

One shortest route is (0,0) → (0,2) → (2,2) → (2,3). Each move crosses only open cells and travels at most 2 cells. A two-move route cannot cover the required horizontal distance of 3 and vertical distance of 2, so the answer is 3.

Example 2

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

The obstacle at (0,2) blocks the only row. A move cannot cross it, even though k is large enough to reach the final column.

Example 3

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

The starting cell is already the open destination, so no move is needed.

Constraints

  • For this exercise, assume 1 <= n, m <= 100 and 1 <= k <= 100.
  • maze is rectangular, with n rows and m columns.
  • Every cell is either 0 or 1.

More Harness problems

See Harness hiring insights
public int getMinimumMoves(int[][] maze, int k) {
    // Write your code here.
}
maze[[0,0,0,0],[1,1,0,0],[0,0,0,0]]
k2
expected3
Checking account…