Sliding Puzzle

Hard Topics Company Tags

The two-row, three-column board contains the numbers 0 through 5 exactly once. The 0 represents the empty space. In one move, swap the empty space with a tile immediately above, below, left, or right of it, staying inside the board. Return the fewest moves needed to reach [[1,2,3],[4,5,0]]. Return -1 if that arrangement cannot be reached.

Example 1:

Sliding Puzzle, example 1: illustration of the example

Input: board = [[1,2,3],[4,5,0]]

Output: 0

Explanation: The board already matches the target arrangement, so no moves are needed.

Example 2:

Sliding Puzzle, example 2: illustration of the example

Input: board = [[1,2,3],[0,4,5]]

Output: 2

Explanation: Move tile 4 left into the empty space, then move tile 5 left. The bottom row changes from [0,4,5] to [4,0,5] to [4,5,0], solving the board in 2 moves.

Example 3:

Sliding Puzzle, example 3: illustration of the example

Input: board = [[2,1,3],[4,5,0]]

Output: -1

Explanation: Only tiles 1 and 2 are exchanged from the target. On this three-column board, legal moves preserve the parity of the number of inverted pairs when the empty space is ignored. This board has odd parity and the target has even parity, so it cannot be solved.

Constraints:

  • board.length == 2
  • Each row contains exactly 3 entries.
  • The numbers 0, 1, 2, 3, 4, and 5 each occur exactly once.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.