TRT
Sign in
hardAdvancedLeetCode#state-space search#A* with Manhattan heuristic

Sliding puzzle

Solve a 2 × 3 sliding-tile puzzle in the fewest moves by searching the graph of board states, with BFS or A*.

The Runtime Theory Team1 min read
Taught inA* and heuristicsPro — members onlyA* is Dijkstra's algorithm with a sense of direction: it orders vertices by distance so far plus an estimate of the distance remaining. If the estimate never overestimates, the path it finds is still optimal, usually after exploring far less.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inboard = [[1, 2, 3], [4, 0, 5]]

out1

inboard = [[1, 2, 3], [5, 4, 0]]

out-1

inboard = [[4, 1, 2], [5, 0, 3]]

out5

A 2 × 3 board holds tiles 1–5 and an empty square 0. A move swaps 0 with an adjacent tile. Return the fewest moves to reach [[1, 2, 3], [4, 5, 0]], or -1 if impossible.

Before you code

Each board is a vertex and each move an edge. There are only 6!/2 = 360 reachable boards from any start, so BFS is enough; A* with a good heuristic explores fewer.

Hints

  1. Encode boards as strings such as "123450", with a precomputed neighbor list for each position of 0.
  2. BFS from the start board; the first time you reach the goal, return the depth.
  3. A* version: h = sum of Manhattan distances of tiles 1–5 to their home squares, which never overestimates.

Production & complexity notes

When solving Sliding puzzle on LeetCode (hard), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in A* and heuristics to reinforce the underlying pattern.

What it practices

Searching an implicit graph with a heuristic, from A* and heuristics.

Not started

Sign in to save your learning progress.

Sign in to save