FunctionRacerProblemsRace

Slide the Tiles Into Place

HardGridsPython, JavaScript, TypeScript, Java, C++

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

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Grids problems