← MAIN
01 // STATE-SPACE SEARCH · PYTHON BACKEND

N-PUZZLE AGENTS

Ten search algorithms solve the sliding puzzle live, with each search streamed from Python.
ALGORITHM — MOVES — NODES — STATUS IDLE

HOW TO PLAY

The goal is to slide the tiles into order, with the blank in the top-left corner. Click a tile next to the blank to slide it, or press an arrow key to move the blank.

Pick an algorithm and press SOLVE. The search streams here as it runs, and the exploration panels show the boards it is expanding.

When a solution is found, PLAY replays it one slide at a time, and STEP moves through it by hand.

Game settings
PUZZLE SETUP
SCRAMBLE DEPTH: 20 RANDOM MOVES
More settings
PUZZLE SIZE
CUSTOM BOARD
AGENT
ALGORITHM
HEURISTIC
Click a tile next to the blank, or press an arrow key. The agents solve from the board shown.
SOLUTION PLAYBACK 0 / 0
COMPARE ALGORITHMS ON THIS BOARD
ConfigurationStatusMovesNodesNodes (log scale)Time
Search log
// Connecting to the Python search server…

HOW IT WORKS

This page runs ten search algorithms on the N-Puzzle, a sliding-tile puzzle on a board from 2 × 2 up to 10 × 10. The best known sizes are the 8-puzzle (3 × 3) and the 15-puzzle (4 × 4). A search starts from the scrambled board and looks for a shortest sequence of slides to the solved board. The methods differ in which board they expand next. The informed methods use a heuristic, an estimate of the moves still needed.

The board, the moves and the goal

A board is a list of n × n tiles read row by row, where n runs from 2 to 10 (n = 3 is the 8-puzzle and n = 4 the 15-puzzle). The number 0 marks the blank square, and the other numbers are the tiles. The code stores a board as a tuple of n² integers, and a tile's index is its position in reading order.1

The goal is the solved board (0, 1, …, n² − 1). Its blank is in the top-left corner, and tile t sits at index t.2 A move slides a tile into the blank, which is the same as the blank moving one square up, down, left or right. A move that would leave the board is not legal. The blank has two legal moves in a corner, three on an edge and four in the middle. The code lists them in the order Up, Down, Left, Right.3

A successor is a board reached by one legal move. The state space is the set of boards reachable from the start, and a search explores it one successor at a time.4

Not every board can reach the goal. Let inv(s) be the number of inversions of board s: the pairs of tiles, not counting the blank, that stand in the wrong order, with the larger tile first. Let b be the index of the blank, so that ⌊b/n⌋ is its row. A board is solvable when the formula below holds.

\text{solvable}(s) \iff \begin{cases} \operatorname{inv}(s) \text{ is even} & n \text{ odd} \\ \operatorname{inv}(s) + \lfloor b/n \rfloor \text{ is even} & n \text{ even} \end{cases}
5

For an odd n, a move never changes the parity of inv(s). For an even n, a vertical move changes inv(s) by n − 1, which is odd, so the row of the blank is needed to keep the parity fixed. Exactly half of all arrangements are solvable, so the 15-puzzle has 16!/2 \approx 1.05 \times 10^{13} reachable boards.

Example. Swapping tiles 1 and 2 on the 8-puzzle gives (0, 2, 1, 3, 4, 5, 6, 7, 8). Its one inversion is odd, so the board cannot reach the goal, and is_solvable returns False for it.

Breadth-first search (BFS)

Breadth-first search expands boards in order of their distance from the start, so every board k moves away is expanded before any board k + 1 moves away. Its frontier, the set of boards generated but not yet expanded, is a first-in, first-out queue. A reached set holds every board generated so far, so no board enters the queue twice. Every move costs 1, so the first arrival at the goal lies on a shortest path.67

The goal test runs when a board is generated, not when it leaves the queue. That finds the goal one full layer of expansions earlier.8

BFS stores every board it reaches, so its memory grows with the number of boards. The server stops any search that stores boards at 250,000 expanded boards up to 4 × 4, and BFS hits that limit on deep 15-puzzle scrambles. Larger boards take more memory per board, so the limit shrinks with the board: 160,000 at 5 × 5 and 40,000 at 10 × 10.9

On the 8-puzzle benchmark, BFS solved all 50 boards optimally. It expanded a mean of 73,756 boards for a mean path of 21.8 moves.10

674
function BFS(start):
    frontier ← queue holding start
    reached ← {start}
    while frontier is not empty:
        board ← remove the oldest board from frontier
        for each move m in LEGAL-MOVES(board):
            child ← RESULT(board, m)
            if child is the goal:
                return the moves from start to child
            if child is not in reached:
                add child to reached
                add child to frontier
    return no solution

Goal test at generation. The full version tests the goal as each child is made, which is why the search returns one layer sooner than a test at removal would. The node holds its parent and move, so the path is rebuilt by walking the parent links back to the start.11

Reached set. A board is added to reached when it is queued, not when it is expanded. Without it a board could enter the queue once for each path that reaches it.

Depth-first search (DFS)

Depth-first search follows one line of moves as far as it can, then backs up to the last choice that is still open. Its frontier is a last-in, first-out stack. It often finds a solution quickly, but that solution is rarely a short one.1213

The code pushes the successors in reverse order, so that they come off the stack in Up, Down, Left, Right order. The goal is tested when a board leaves the stack. A board that is already expanded or already on the stack is not pushed again.14

On the 8-puzzle benchmark no DFS path was optimal (0 of 50). Its mean path was 43,671.8 moves, against 21.8 for BFS, and it expanded a mean of 79,209 boards.10

1213
function DFS(start):
    stack ← [start]
    done ← empty set
    while stack is not empty:
        board ← pop the top of stack
        if board is the goal:
            return the moves from start to board
        add board to done
        for each child of board:
            if child is not in done and not on stack:
                push child onto stack
    return no solution

Reverse push order. Pushing the successors in reverse makes the last one pushed, the Up move, the first one popped. The search therefore prefers Up, then Down, Left and Right, at every board.

Iterative deepening search (IDS)

Iterative deepening search runs depth-first search with a depth limit that starts at 0 and grows by one each round. Each round repeats the work of the earlier rounds, but those repeats are cheap, because the number of boards grows quickly with depth. The first round that finds the goal has found a shortest path, so IDS is optimal. It keeps only the current path in memory.15

IDS is the IDA* procedure below with the heuristic set to zero, so its bound is the depth limit. Since only the path is stored, IDS may expand up to 3,000,000 boards, against 250,000 for the searches that store every board.16

Uniform-cost search (UCS)

Uniform-cost search is best-first search with the priority g alone, where g is the number of moves from the start. Its frontier is a priority queue, so the board with the smallest g is expanded next. When every move costs 1, UCS returns the same lengths as BFS, with more bookkeeping.1718

On the 8-puzzle benchmark UCS was optimal on all 50 boards. It expanded a mean of 88,444 boards.10

Bidirectional BFS

Bidirectional BFS runs a breadth-first search from the start and another from the goal at the same time. Each step expands one whole layer on whichever side has the smaller layer. Each search covers about half the depth of the solution, so far fewer boards are expanded. When a board generated on one side is already in the other side's table, the two halves join into a solution.19

The code records the total length through each meeting board and keeps the cheapest one in the layer. Each move from the goal side is stored as the move that led from the goal toward the board, so JOIN reverses it with INVERSE when it rebuilds the path from the goal end.20

On the 8-puzzle benchmark, bidirectional BFS was optimal on all 50 boards. It expanded a mean of 1,941 boards, against 73,756 for BFS.10

21
function BIDIRECTIONAL-BFS(start):
    layers ← ([start], [goal])
    seen ← ({start}, {goal})
    while both layers are not empty:
        expand the smaller layer one full layer:
            for each board in that layer:
                for each child of board:
                    if child is new on this side:
                        add child to the next layer
                        if child was seen on the other side:
                            record the meeting point and its total length
        if a meeting point was found in this layer:
            return the path through the cheapest meeting point
    return no solution

Smaller layer first. Expanding whichever side has the smaller layer keeps the work low. Each step adds one full layer, so the two searches meet at about half the solution depth.

Meeting cost. A meeting board gives a path of length depth + 1 plus the other side's depth. The search does not stop at the first meeting it sees: it takes the smallest total in that layer. On the benchmark, every path it returned was optimal.

Heuristics

A heuristic h(s) estimates the number of moves from board s to the goal. It is admissible if it never overestimates the true distance h*(s), so that h(s) ≤ h*(s) for every board s. A search that uses an admissible heuristic in A* or IDA* returns an optimal path. Every heuristic on this page except the neural one is admissible.

Manhattan distance adds, for each tile, the number of rows plus the number of columns between the tile and its goal square. The blank is not counted.22

h_{\text{M}}(s) = \sum_{t \neq 0} \Big( \big|\lfloor p_t/n \rfloor - \lfloor t/n \rfloor\big| + \big|(p_t \bmod n) - (t \bmod n)\big| \Big)
23

Here p_t is the index of tile t on board s. Its goal index is t itself, so \lfloor t/n \rfloor is its goal row and t \bmod n its goal column. A move slides one tile by one square, so it lowers the sum by at most 1. That is why the heuristic never overestimates.

Linear conflict adds a penalty to Manhattan distance for tiles that block each other in their goal line. Two tiles conflict when both belong in the same row (or column) and stand there in reverse order. One of them must leave the line and come back, two moves that Manhattan distance does not count. For each line, the code counts the tiles that must leave, which is the number of tiles minus the longest increasing run of their goal positions, and adds 2 for each.24

\begin{aligned} h_{\text{LC}}(s) &= h_{\text{M}}(s) + 2 \sum_{\ell=0}^{n-1} \Big( r^{\text{row}}_\ell(s) + r^{\text{col}}_\ell(s) \Big) \\ r^{\text{row}}_\ell(s) &= k^{\text{row}}_\ell - \operatorname{LIS}\big(q^{\text{row}}_\ell\big) \end{aligned}
2526

Here q^{\text{row}}_\ell is the list of goal columns of the tiles on row \ell whose goal row is \ell, in board order from left to right, and k^{\text{row}}_\ell is its length. The function LIS gives the length of the longest strictly increasing subsequence of a list. The removal count r is the fewest tiles to take out of the line so that the rest are in goal order. The column term r^{\text{col}}_\ell is built the same way from the goal rows of the tiles on column \ell whose goal column is \ell, read from top to bottom. The code adds 2 for each removed tile, the rule's constant.

Example. On the board (2, 1, 0, 3, 4, 5, 6, 8, 7), the top row holds tiles 2 and 1, with goal columns 2 and 1, so its longest increasing subsequence has length 1 and r = 1. The bottom row gives another removal, so h_{\text{M}} = 4 and h_{\text{LC}} = 4 + 2 \times 2 = 8. The true distance is 20 moves, found by BFS, so both values stay below it.

Pattern database (PDB, 4 × 4 only) splits the 15 tiles into three groups of five: (1, 2, 3, 6, 7), (4, 5, 8, 9, 12) and (10, 11, 13, 14, 15). For each group, a table gives the exact number of moves that the group's own tiles need to reach their goal squares, with every other tile treated as unlabelled. A move of another tile costs 0 in the table, so the three groups never count the same move twice. Their values can therefore be added, and the sum is admissible. It is far stronger than Manhattan distance, which ignores every interaction between tiles.27

h_{\text{PDB}}(s) = \sum_{g=1}^{3} T_g\big[k_g(s)\big], \qquad k_g(s) = \sum_{j=1}^{5} p_{g,j}(s)\cdot 16^{\,5-j}
2829

Here T_g is the table for group g, with 16⁵ = 1,048,576 entries, one for each key. The value p_{g,j}(s) is the index on board s of the j-th tile of group g. The key k_g(s) writes those five positions as base-16 digits, with the first tile most significant. Each table is built by a 0-1 breadth-first search from the goal. A blank move that swaps with a tile of the group costs 1, and any other blank move costs 0. The first time a key is reached gives its minimum cost over all blank positions. The finished tables are committed as a data file, so the server loads them instead of building them.3031

Neural correction (4 × 4 only) is the learned heuristic. It adds a neural network's output to the pattern database. A neural network is a function whose weights are learned from data. Here its input x(s) is a one-hot encoding of the board: 256 features, one for each pair of an index and a tile, where feature 16i + t is 1 if tile t sits at index i. The network is two residual blocks of 512 units, and the ReLU activation is \max(z, 0).3233

\begin{aligned} h(s) &= h_{\text{PDB}}(s) + \operatorname{softplus}\big(\operatorname{net}(s)\big), \qquad h(\text{goal}) = 0 \\ a_0 &= \operatorname{ReLU}(W_{\text{in}}\,x + b_{\text{in}}) \\ y_k &= \operatorname{ReLU}(W_{k,1}\,a_k + b_{k,1}) \\ a_{k+1} &= \operatorname{ReLU}(a_k + W_{k,2}\,y_k + b_{k,2}), \qquad k = 0, 1 \\ \operatorname{net}(s) &= w_{\text{out}}^{\top} a_2 + b_{\text{out}} \end{aligned}
3334

Here \operatorname{softplus}(z) = \log(1 + e^{z}) is a smooth function that is always positive, so the network can only add to the pattern database value. The total is never below the pattern database. The weights W, b and w_{\text{out}} are learned. The network starts with zero output weights and an output bias of −4, so h starts near the pattern database, since \operatorname{softplus}(-4) \approx 0.018.3536

The neural heuristic is not admissible. It can overestimate, so A* and IDA* can return longer than optimal paths. The server runs it only with batch weighted A*.37

Greedy best-first search

Greedy best-first search orders the frontier by h alone and ignores g, the moves already made. It heads straight for the boards that look closest to the goal, which makes it fast. Its estimate can lead it into dead ends, though, so the path it returns is often long.3839

On the 8-puzzle benchmark, greedy search expanded a mean of 267 boards. Only 5 of 50 paths were optimal, and the mean path was 40.7 moves against 21.8.10

A* search

A* orders the frontier by f = g + h. Here g is the depth of a board, the number of moves from the start along the path found, and h is the heuristic estimate of the moves left. The code computes f for each generated board and keeps the frontier in a priority queue.4038

f(s) = g(s) + h(s)
40

Ties in f go to the board with the larger g, which has the smaller h and is nearer the goal. When h is admissible, the first board to leave the frontier is the goal, along a shortest path. A board reached again by a shorter path has its key lowered in place (decrease-key). The heap has no such operation, so the code adds a new entry and marks the old one stale.4142

On the 8-puzzle benchmark A* was optimal on all 50 boards. It expanded a mean of 771 boards with Manhattan distance, and 404 with linear conflict.10

4342
function A-STAR(start):
    frontier ← priority queue holding start, keyed by f = g + h
    done ← empty set
    while frontier is not empty:
        board ← remove the entry with the smallest f
        if board is the goal:
            return the moves from start to board
        add board to done
        for each child of board:
            if child is not in done:
                g ← g(board) + 1
                if child is in frontier with a larger g:
                    lower child's key to g + h(child)
                else if child is not in frontier:
                    add child to frontier with key g + h(child)
    return no solution

Other keys. The same loop becomes the other best-first searches by changing the priority: UCS uses g, greedy uses h, and weighted A* uses g + w·h with the tie-break on −g.44

Lazy deletion. A stale entry is an old frontier entry for a board whose key has been lowered. The pop step skips it, so the heap never has to find and move an entry. The frontier's length counts only the live boards.41

Weighted A*

Weighted A* uses f = g + w·h, where the weight w is at least 1. The default is w = 2, and the page slider goes from 1 to 5. A larger weight gives the estimate more say than the distance already travelled, so the search reaches the goal after fewer expansions. The path can be longer, though. With an admissible h, the path is at most w times the optimal length.45

f(s) = g(s) + w\,h(s), \qquad w = 2 \text{ by default}
45

Here g(s) is the depth of board s, h(s) its heuristic, and w the weight. With w = 1 the formula is A*.

On the 8-puzzle benchmark, with w = 2 and Manhattan distance, weighted A* expanded a mean of 313 boards. Its paths were optimal on 20 of 50 boards, with a mean gap of 8.7%. The gap of a path is (its moves − the optimal moves) divided by the optimal moves.10

IDA* search

IDA* (iterative-deepening A*) runs a depth-first search with a bound on f, where the depth limit of IDS would be. Boards with f above the bound are cut off, and the search remembers the smallest f among the boards it cut off. If no goal is found, the next round uses that value as its bound. The bound therefore rises to the next f that any board actually has.4647

The search keeps only the current path in memory, so its memory grows with the solution length, not with the number of boards. The price is repeated work, because every round repeats the earlier ones. The code does not record the boards it has visited, so a board can be expanded more than once. It does skip the move that undoes the previous one.48

The heuristic is updated in constant time rather than recomputed. When the blank swaps with a tile, only that tile's contribution changes. For Manhattan distance, the change is the difference of two table entries. For the pattern database, only the key of the tile's group changes. Linear conflict is recomputed from the board.49

On the 8-puzzle benchmark IDA* was optimal on all 50 boards. It expanded a mean of 2,090 boards with Manhattan distance, and 1,024 with linear conflict.10

On the 15-puzzle, the median IDA* run with the pattern database expanded 598,988.5 boards over the first 40 boards of the 100-board test set. The test set's optimal costs were computed by that same search.5051

4752
function IDA-STAR(start):
    bound ← h(start)
    while true:
        result ← SEARCH(start, g = 0, bound)
        if result is FOUND:
            return the moves on the path
        if result is infinity:
            return no solution
        bound ← result                               # the smallest f that was cut off

function SEARCH(board, g, bound):
    f ← g + h(board)
    if f > bound:
        return f                                     # cut off; report f
    if board is the goal:
        return FOUND
    smallest ← infinity
    for each move m from board, except the undo of the last move:
        result ← SEARCH(RESULT(board, m), g + 1, bound)
        if result is FOUND:
            return FOUND
        smallest ← min(smallest, result)
    return smallest

Repeated work. IDA* repeats the earlier rounds each time the bound rises. The repeats cost little when the tree grows quickly with each extra move, because the last round dominates the total.

Incremental heuristic. The blank moves one square, so only the moved tile changes its place. Manhattan distance and the pattern database each need only a few table lookups per move, and UNDO-H restores the pattern database key when the child returns.53

Batch weighted A* (BWAS)

Batch weighted A* (BWAS) is weighted best-first search built for a heuristic that is slow to call one board at a time, such as the neural network. Each step pops up to 100 boards by default, expands them, and scores every new child in one batched heuristic call. Sharing one call across many boards removes most of the per-call overhead of Python.5455

The priority is f = g_weight · g + h, with g_weight = 0.8 by default and a range from 0.1 to 1. A weight below 1 favours boards that the heuristic rates close to the goal. That is faster, but the path is not guaranteed to be optimal, even with an admissible heuristic.5657

f(s) = g_{\text{weight}}\, g(s) + h(s), \qquad g_{\text{weight}} = 0.8 \text{ by default}
54

Here g(s) is the depth of board s. A board can sit in the heap several times, once for each cheaper path found to it. An entry whose g is no longer the best is stale and is skipped. A board is closed when it leaves the heap, so it is never expanded twice.5859

54
function BWAS(start):
    heap ← [start with priority h(start)]
    while heap is not empty:
        batch ← up to batch-size boards popped from heap
        if batch is empty:
            return no solution
        for each board in batch:
            if board is the goal:
                return the moves from start to board
            close board
            for each child of board:
                if child is not closed and reached by a cheaper path:
                    record the cheaper path to child
                    add child to new
        h-values ← HEURISTIC-BATCH(new)              # one call for every new child
        push each child in new with key g_weight · g + h
    return no solution

Batches. The batch size only changes how many boards are popped per step, and so how many children share one heuristic call. The priorities and the closed rule do not depend on it.

Closed boards. The closed set marks a board as expanded when it leaves the heap. A board reached by a cheaper path while it waits in the heap gets a second entry, and the stale test removes the older entry when it is popped.

Goal test on removal. The goal is recognised when it is popped into a batch, not when it is generated, so the cheapest path to the goal is the one that gets returned.

Training the neural heuristic

The network is trained by approximate value iteration, the method behind DeepCubeA, and it uses no solver labels. Value iteration sets each board's value to its immediate cost plus the smallest value among its successors, and repeats until the values settle. Here every move costs 1 and the goal's value is 0.60

Each round samples 50,000 boards by random walks from the goal. A walk's length is drawn uniformly from 0 to 200 moves, and a walk never undoes its previous move. The targets are computed with a frozen copy of the network, called the target network. The network is then fitted to those targets with Adam, a gradient method with its own step size for each weight, at a learning rate of 0.001 and on minibatches of 1,000. The target network is then replaced by a copy of the fitted network.616263

y(s) = \begin{cases} 0 & s \text{ is the goal} \\ 1 + \min_{a \text{ legal in } s} \bar h(s_a) & \text{otherwise} \end{cases}
64

Here \bar h is the heuristic of the target network, and s_a is the board after move a. Each board's target is one more than the smallest value among its legal successors, so the values spread outward from the goal one move at a time.

L = \frac{1}{B} \sum_{i=1}^{B} \big( h(s_i) - y_i \big)^2
65

Here L is the mean squared error on a minibatch, B is its size (1,000 by default), and h is the network's heuristic.

Every 10 rounds the script scores the network against the 100 boards of the 15-puzzle test set, whose optimal costs are known. The mean absolute error is the average of |h(s) - h^*(s)|, and the overestimate rate is the share of boards with h(s) > h^*(s).66

The committed log has 172 rounds over 42.3 minutes. At round 170, the mean absolute error was 2.84 against 12.22 for the pattern database alone, and the network overestimated on 46% of the boards.67

The shipped weights are the final export after round 172, which the log does not evaluate. The network size, the 50,000-board batch and the 200-move walk length are the script's defaults. The log does not record those settings, and no sweep is recorded.6862

Benchmark results

The table compares the configurations on 50 random 8-puzzle boards, drawn with a fixed seed. Each row ran every board with the same limits. The gap is the same measure as in weighted A* above.6910

ConfigurationSolvedMean nodesMean time (s)Mean costOptimal pathsMean gap
bfs50/5073,7561.07921.850/500.0%
dfs50/5079,2091.53743671.80/50202380.3%
ucs50/5088,4442.09621.850/500.0%
bibfs50/501,9410.01221.850/500.0%
greedy50/502670.00640.75/5087.2%
astar50/507710.02221.850/500.0%
wastar50/503130.01223.620/508.7%
idastar50/502,0900.01121.850/500.0%
astar+lc50/504040.02921.850/500.0%
idastar+lc50/501,0240.03321.850/500.0%

Limits on the server

Every search runs in Python on the server and streams its progress to the page over a WebSocket. A search stops after 10 seconds.70

A search that stores every board stops at 250,000 expanded boards. IDS and IDA* keep only the current path, so they may run to 3,000,000 expanded boards before the limit applies.71

The pattern database and the neural heuristic cover the 4 × 4 board only, so the 8-puzzle menu leaves them out. The server runs the neural heuristic with batch weighted A* alone.7273