Six-Tile Slider

HardGraphs

Problem

A pocket puzzle has a 2 × 3 tray holding tiles 1 to 5 and one empty slot, written as 0. A move slides a tile that is horizontally or vertically next to the empty slot into it.

Given the current tray board, return the minimum number of moves to reach [[1,2,3],[4,5,0]], or -1 if that arrangement can never be reached.

Example 1

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

Slide 4 left, then slide 5 left.

Example 2

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

Swapping just two tiles is impossible with slides alone.

Constraints

  • board is 2 × 3
  • board contains each of 0, 1, 2, 3, 4, 5 exactly once

Hint

Show the first hint

There are only 6! = 720 possible trays. Treat each tray as a node.

Walkthrough

How to approach it

01Clarify before coding

  • Does every move count as 1, whichever tile moves? Yes.
  • Can the puzzle be unsolvable? Yes, half of all arrangements are; return -1 for them.
  • Is the target fixed? Yes, [[1,2,3],[4,5,0]].

02Brute force

DFS over move sequences with a depth limit, increasing the limit until the target is found.

Cost: Branching factor 2–3 to the power of the answer (up to the low twenties), and no way to detect unsolvable trays without exhausting everything.

The rest of the walkthrough is in the app

The full walkthrough (key insight, step-by-step, dry run, complexity, edge cases, pitfalls, follow-ups) and solutions in Python and JavaScript are in the app, next to an editor and a terminal that runs your code against the tests.

This problem is part of Pro.