Loading content...
You are presented with a 2×3 grid containing five numbered tiles (labeled 1 through 5) and one empty cell (represented by 0). The empty cell allows adjacent tiles to slide into its position—this is the only permissible operation.
In each move, you may select any tile that is horizontally or vertically adjacent to the empty cell and slide it into the empty position (effectively swapping the tile and the empty cell).
Your objective is to rearrange the tiles from any given initial configuration into the target configuration:
[[1, 2, 3],
[4, 5, 0]]
In the solved state, tiles are arranged in ascending order from left to right, top to bottom, with the empty cell occupying the bottom-right corner.
Return the minimum number of moves required to transform the initial board into the solved configuration. If the puzzle is unsolvable from the given starting position, return -1.
board = [[1,2,3],[4,0,5]]1The puzzle is just one move from the solution. Slide tile 5 leftward into the empty position (or equivalently, move the empty cell to the right), resulting in [[1,2,3],[4,5,0]].
board = [[1,2,3],[5,4,0]]-1This configuration is mathematically impossible to solve. The tiles 4 and 5 are swapped compared to the goal state, and no sequence of valid moves can correct this inversion—the puzzle's parity makes it unsolvable.
board = [[4,1,2],[5,0,3]]5The minimum solution requires exactly 5 moves. One optimal sequence: [[4,1,2],[5,0,3]] → [[4,1,2],[0,5,3]] → [[0,1,2],[4,5,3]] → [[1,0,2],[4,5,3]] → [[1,2,0],[4,5,3]] → [[1,2,3],[4,5,0]].
Constraints