Slide the Tiles Into Place
board is a sliding puzzle with 2 rows and 3 columns. It holds the tiles 1 to 5 and one empty space, written 0. A move slides a tile that is directly above, below, left or right of the space into the space.
Return the fewest moves that turn board into goal, or -1 if no sequence of moves does.
Example 1
board [[0,1,3],[4,2,5]]
goal [[1,2,3],[4,5,0]]
returns 3
Slide 1 left, then 2 up, then 5 left. The space has to travel three cells, so fewer moves cannot work.
Example 2
board [[2,1,3],[4,5,0]]
goal [[1,2,3],[4,5,0]]
returns -1
Only the tiles 1 and 2 are swapped. No sequence of slides swaps just two tiles.
Example 3
board [[3,0,5],[1,4,2]]
goal [[3,0,5],[1,4,2]]
returns 0
The board already matches.
Constraints
boardandgoalboth have 2 rows of 3 numbers- each holds every number from 0 to 5 exactly once
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.
More Grids problems
- Wall Off the OutbreakHard
- Water Held by the LandHard
- Column TotalsBeginner
- Count Negatives in a Sorted GridBeginner
- Cross TotalBeginner
- Enlarge the PictureBeginner
- Frame TotalBeginner
- Heaviest RowBeginner