A* solves the 8-puzzle by searching boards in order of estimated total cost: the moves already made, plus a Manhattan-distance guess for the work still left. When that guess never overshoots, the first path A* reaches the goal on is a shortest path.
The rest of this page walks through that method, the solvability test you should run before any search, and a short Python example. When you want to see a shortest 3×3 path on a board of your own, this site's numbered 3×3 and 4×4 solver will play the moves one at a time.
What A* does on the 8-puzzle
The 8-puzzle is a 3×3 board with tiles 1 through 8 and one blank. A legal move slides a tile that sits next to the blank into the empty square. The usual goal, and the one used on this site, is tiles in reading order with the blank in the bottom-right corner: 1 2 3 / 4 5 6 / 7 8 0.
A* keeps a frontier of boards it has reached. Each board has two numbers: g, the number of slides already used to get there, and h, a heuristic estimate of how many slides are still needed. The algorithm always expands the board with the smallest f = g + h. It also remembers boards it has already finished with, so it does not expand the same arrangement twice.
That is the whole control loop. There is no special 8-puzzle rule inside A* itself. What makes the search practical — and what makes the first solution shortest — is the heuristic, which on this page is Manhattan distance with weight 1.
Why the search is finite
A 3×3 board has 9! = 362,880 ways to place the eight tiles and the blank, and only half of those arrangements can reach the goal by sliding. That reachable half is 181,440 boards, so a correctly written search cannot wander forever. It will either find the goal or exhaust the reachable set.
Manhattan distance as the heuristic
Manhattan distance for the 8-puzzle is the sum, over every numbered tile, of how many rows plus how many columns that tile sits away from its goal square. The blank is left out of the sum. Each slide moves one tile by one square, so a tile that is three squares away in this sense still needs at least three slides of its own.
Because the sum only counts those unavoidable steps, Manhattan distance never claims that a board is closer to the goal than it really is. In the language of A*, the heuristic is admissible. When h is admissible and A* expands the lowest f first, the first time the goal is selected it has been reached in the fewest slides possible.
A weaker alternative, often taught alongside this one, is the misplaced-tile count: how many numbered tiles are not yet in their goal squares. That number is also admissible, but it is a looser lower bound, so A* usually expands many more boards before it finishes.
If you want a demanding test case after the method is clear, the two 8-puzzle boards that take 31 moves are the longest shortest paths on the 3×3.
Why Manhattan distance does not overshoot
Suppose tile 8 is two rows and one column away from its goal. It must move at least three times, because one slide changes only one of those coordinates, and no other tile's motion can reduce that minimum for tile 8. Adding the same minimum for every other numbered tile still does not over-count, because a single slide advances only one tile. The sum is therefore a safe underestimate of the remaining work.
A solvability check comes first
Before A* runs on an 8-puzzle, check whether the start board can reach the goal at all. If it cannot, no search will help, and you should return that answer instead of looking for a path.
The test for a 3×3, with the goal above, is the inversion count. Read the eight numbered tiles in order, skipping the blank, and count every pair in which a larger number appears before a smaller one. If that count is even, the board is solvable; if it is odd, it is not.
The same idea, with the blank's row included, is what you use on a 4×4. The famous case of two tiles swapped in an otherwise finished 15-puzzle is why a 14-15 swap cannot be solved by sliding.
Even and odd inversion counts
A finished board has inversion count 0, which is even. Swapping 7 and 8 on that finished board, and leaving the blank in the corner, produces exactly one inversion. That position is odd, and A* should not be asked to solve it. The function in the Python section below returns no path in that case, rather than searching until the frontier is empty.
A Python 8-puzzle solver with A*
The example below is a compact 8-puzzle solver in Python. It uses the inversion test, Manhattan distance, and A* with f = g + h. The return value is the sequence of tiles that slide into the blank, which matches how this site's solver highlights each move. Boards are written left to right, top to bottom, with 0 for the blank.
import heapq
GOAL = (1, 2, 3, 4, 5, 6, 7, 8, 0)
def manhattan(board):
distance = 0
for index, tile in enumerate(board):
if tile == 0:
continue
goal_index = tile - 1
distance += abs(index // 3 - goal_index // 3) + abs(index % 3 - goal_index % 3)
return distance
def inversion_count(board):
tiles = [tile for tile in board if tile != 0]
count = 0
for i, a in enumerate(tiles):
for b in tiles[i + 1:]:
if a > b:
count += 1
return count
def is_solvable(board):
return inversion_count(board) % 2 == 0
def neighbors(board):
blank = board.index(0)
row, col = divmod(blank, 3)
result = []
for d_row, d_col in ((-1, 0), (1, 0), (0, -1), (0, 1)):
n_row, n_col = row + d_row, col + d_col
if 0 <= n_row < 3 and 0 <= n_col < 3:
swap_with = n_row * 3 + n_col
new_board = list(board)
tile = new_board[swap_with]
new_board[blank], new_board[swap_with] = new_board[swap_with], new_board[blank]
result.append((tuple(new_board), tile))
return result
def astar(start):
start = tuple(start)
if not is_solvable(start):
return None
came_from = {start: (None, None)}
g_score = {start: 0}
heap = [(manhattan(start), 0, start)]
seen = set()
while heap:
_, g, node = heapq.heappop(heap)
if node in seen:
continue
seen.add(node)
if node == GOAL:
tiles = []
current = node
while came_from[current][0] is not None:
previous, tile = came_from[current]
tiles.append(tile)
current = previous
tiles.reverse()
return tiles
for nxt, tile in neighbors(node):
tentative = g + 1
if tentative < g_score.get(nxt, float("inf")):
g_score[nxt] = tentative
came_from[nxt] = (node, tile)
heapq.heappush(heap, (tentative + manhattan(nxt), tentative, nxt))
return None
board = (1, 2, 3, 4, 5, 6, 7, 0, 8)
print(astar(board))
On that one-move board, the printed list is [8]: tile 8 slides down into the blank and the puzzle is finished. For an unsolvable start such as (1, 2, 3, 4, 5, 6, 8, 7, 0), astar returns None.
This example is for the 8-puzzle only. The 15-puzzle has a much larger space, and a shortest-path search needs a stronger design than the listing above.
How to read the output
Each number in the list is the tile that moves on that step, not the destination square and not a direction letter. The length of the list is the number of slides. If you step through the list on the start board, you should finish at 1 2 3 / 4 5 6 / 7 8 0.
To try a 3×3 game rather than a typed-in board, play a 3×3 slide puzzle on the homepage.