FastPrepSliding Puzzle

Sliding Puzzle

NVIDIA logoNVIDIA● HardFULLTIMEPHONE SCREEN
Learn

Problem statement

The 2 x 3 board contains tiles 1 through 5 and one empty cell 0. In one move, swap the empty cell with a tile directly above, below, left or right of it.

Return the minimum moves needed to reach [[1,2,3],[4,5,0]]. Return -1 if the target is unreachable.

Function

slidingPuzzle(board: int[][]) → int

Examples

Example 1

board = [[1,2,3],[4,0,5]]return = 1

Swap the empty cell with tile 5.

Example 2

board = [[1,2,3],[5,4,0]]return = -1

Swapping the two numbered tiles changes the component; no sequence reaches the target.

Example 3

board = [[4,1,2],[5,0,3]]return = 5

The shortest path uses five legal swaps.

Constraints

  • board has exactly two rows and three columns.
  • Its six cells contain each integer from 0 through 5 exactly once.

More NVIDIA problems

See NVIDIA hiring insights
public int slidingPuzzle(int[][] board) {
    // Write your code here.
}
board[[1,2,3],[4,0,5]]
expected1
Checking account…