Skip to main content
← Sliding Puzzle problem

Sliding Puzzle worked solution

Sliding Puzzle video walkthrough

Worked solution

How do you find the fewest slides?

A tile beside the gap can slide into it. That part is easy. The trouble comes when several tiles can move. Slide one the wrong way and you may spend the next move putting it back.

Treat each whole board as a place you can visit. One slide takes you to a neighbouring board. Breadth-first search can find the shortest route by trying everything one slide away, then two slides away. That’s practical on the judge’s little 2 × 3 board. On the larger 3 × 3 puzzle, A* search gives us a way to choose which board to try first.

For each numbered tile, count how many rows and columns it still has to travel. Add those distances. A* tries the board with the smallest slides already taken + estimated slides left. Each slide moves one numbered tile by one square, so the estimate can never ask for more moves than the puzzle actually needs.

Side note Why leave the blank out of Manhattan distance?
Reading note

Why leave the blank out of Manhattan distance?

Take the judge’s two-row puzzle with just one tile out of place. The top row is finished. In the bottom row, slide 5 left into the gap and the puzzle is solved.

Sliding tile 5 left once puts the last row in order.
The dashed square follows the tile. Both change position in a single move.

Tile 5 was one square from home. The blank was also one square from home. Counting both would predict at least two moves for a puzzle you just solved in one.

Counting only numbered tiles gives A* a dependable lower bound. One slide can bring just one numbered tile one square closer to home. Some boards need detours, so the actual solution can be longer than the estimate.

For a three-column board, add the row difference and column difference for each numbered tile. Skip 0.

Princeton’s 8-puzzle assignment on Manhattan priority

Link to this answer

Four slides solve the 8-puzzle

Look at the first board below. The top row is finished. Tiles 4, 5, 7 and 8 are each one square from home. Before we move anything, we know a solution must take at least four slides.

The same 3 × 3 board at the start, after moving 5 and 4, and after moving 7 and 8. Each pair of moves puts two tiles home.
Follow the dashed gap. It starts in the centre, reaches the bottom left after two slides, then moves across to the bottom right.
  1. Slide 5 right into the middle. That leaves three squares of tile travel, so A* scores this board 1 + 3 = 4. Had we moved 6 left instead, it would be farther from home and the score would be 1 + 5 = 6. The heap prefers the move with 5.
  2. Slide 4 up. The middle row reads 4, 5, 6. The bottom row starts with the gap.
  3. Slide 7 left, then 8 left. The bottom row reads 7, 8, blank. Four slides meet our lower bound, so no shorter solution exists.
Side note How can you tell a sliding puzzle is impossible?
Reading note

How can you tell a sliding puzzle is impossible?

Swap just 7 and 8 on the finished 3 × 3 board. Read the numbered tiles across the rows and skip the blank. One pair is in the wrong order. Each such pair is called an inversion, and the goal has zero.

Sliding 1 down creates two inversions at once.
Read left to right, skipping the blank. One vertical slide changes 1, 2, 3, 4, 5 into 2, 3, 1, 4, 5.

A sideways slide leaves the numbered sequence alone. A vertical slide on a three-column board moves one tile past two others in that sequence. In the picture, moving 1 down makes both 2 and 3 come before it. The inversion count can rise by two, drop by two or stay the same.

Even stays even and odd stays odd. A board with one inversion can never reach the goal with zero. For both three-column puzzles here, even parity also means the board can be solved.

The width matters. An even-width puzzle such as the 15-puzzle also needs the blank’s row in its solvability test.

Princeton’s explanation of solvable boards

Link to this answer

How much work does A* do?

Only half the arrangements can reach the ordered goal. That gives the 2 × 3 puzzle 360 reachable boards and the 3 × 3 puzzle 181,440. A* can finish after exploring only a fraction of them. Boards with many similar estimates can make it explore much more.

For either fixed board size, scoring a board and generating its neighbours take bounded work. If the search encounters S different boards, it uses O(S log S) time for heap operations and O(S) space for the heap, best costs and parents.

Python solution for Sliding Puzzle

The code handles both board sizes above. The search keeps a parent for each improved board so you can replay a shortest solution. The judge wants a count, so the final method returns one fewer than the number of boards in that replay. An impossible board returns -1.

from heapq import heappop, heappush
from itertools import count

def manhattan(board: tuple[int, ...]) -> int:
    total = 0
    for index, tile in enumerate(board):
        if tile == 0:
            continue
        row, col = divmod(index, 3)
        goal_row, goal_col = divmod(tile - 1, 3)
        total += abs(row - goal_row) + abs(col - goal_col)
    return total


def neighbors(board: tuple[int, ...]):
    blank = board.index(0)
    row, col = divmod(blank, 3)
    for dr, dc in ((-1, 0), (0, -1), (0, 1), (1, 0)):
        nr, nc = row + dr, col + dc
        if 0 <= nr < len(board) // 3 and 0 <= nc < 3:
            other = 3 * nr + nc
            moved = list(board)
            moved[blank], moved[other] = moved[other], moved[blank]
            yield tuple(moved)


def solvable(board: tuple[int, ...]) -> bool:
    tiles = [t for t in board if t != 0]
    inversions = sum(a > b for i, a in enumerate(tiles) for b in tiles[i + 1:])
    return inversions % 2 == 0


def a_star_puzzle(start: tuple[int, ...]) -> list[tuple[int, ...]] | None:
    if not solvable(start):
        return None
    goal = (*range(1, len(start)), 0)
    best = {start: 0}
    parent: dict[tuple[int, ...], tuple[int, ...] | None] = {start: None}
    serial = count()
    h0 = manhattan(start)
    frontier = [(h0, h0, next(serial), 0, start)]

    while frontier:
        _, _, _, cost, board = heappop(frontier)
        if cost != best[board]:
            continue
        if board == goal:
            path = []
            curr: tuple[int, ...] | None = board
            while curr is not None:
                path.append(curr)
                curr = parent[curr]
            return path[::-1]

        for nxt in neighbors(board):
            candidate = cost + 1
            if candidate < best.get(nxt, float("inf")):
                best[nxt] = candidate
                parent[nxt] = board
                h = manhattan(nxt)
                heappush(frontier, (candidate + h, h, next(serial), candidate, nxt))

    return None


class Solution:
    def slidingPuzzle(self, board: list[list[int]]) -> int:
        start = tuple(tile for row in board for tile in row)
        path = a_star_puzzle(start)
        return -1 if path is None else len(path) - 1

View the Python source on GitHub ↗

Try the 3 × 3 sliding puzzle

Slide a tile next to the gap, or step through the A* solution. Watch how the estimate changes when one numbered tile moves.

0

Click any tile adjacent to 0 to slide

Moves g(n)
0
Manhattan h(n)
4
Score f = g + h
4
Inversions
2 (Even)
Initial board: g = 0, h = 4 (numbered tiles 1..8 only), f = 4.
Step 1 / 5 · 5 states popped (out of 181,440 reachable)
Learn These Concepts Before SolvingStudy highlighted concepts first
→A* Search→Graph BFSComing soon→Hash SetComing soon

Practise first with Open the Lock

Swim in Rising Water walkthrough →

← Back to practice

Opening sign-in…