Swap tiles 14 and 15 on an otherwise solved board. The result looks one move away from finished, yet there is no legal path back. A 15-puzzle solver should tell you that before it searches anything. It should also let you cancel when a reachable board takes a while.
This tutorial builds a vanilla JavaScript solver around those two requirements. We'll check parity, use Manhattan distance plus linear conflict to cut down the search, then pause and resume IDA* between browser tasks. Copy the JavaScript blocks into one file in order, or paste them together into a modern browser console.
Reject unreachable boards with parity
Use a flat array of sixteen integers in row-major order, with 0 as the blank. The goal is 1 through 15 followed by 0. Each move slides one numbered tile into an orthogonally adjacent blank.
An inversion is a pair of numbered tiles that's out of order in the flattened board. A horizontal slide leaves that order intact. A vertical slide makes one tile cross three numbered tiles, flipping the parity of the inversion count and the parity of the blank's row at the same time.
On a 4×4 board with this goal, a board is reachable exactly when inversions + blankRowFromBottom is odd. Count the bottom row as row 1. The solved board gives 0 + 1, and the swapped 14/15 board gives 1 + 1. Johnson and Story's original proof
const WIDTH = 4; const SIZE = WIDTH * WIDTH; const rowOf = index => Math.floor(index / WIDTH); const columnOf = index => index % WIDTH; function readBoard(input) { if (!Array.isArray(input) || input.length !== SIZE) { throw new TypeError("Expected a flat array of 16 integers"); } const board = [...input]; if ( board.some(tile => !Number.isInteger(tile) || tile < 0 || tile >= SIZE) || new Set(board).size !== SIZE ) { throw new TypeError("Use every integer from 0 to 15 exactly once"); } return board; } function isSolvable(board, blank) { let inversions = 0; for (let left = 0; left < board.length; left++) { if (board[left] === 0) continue; for (let right = left + 1; right < board.length; right++) { if (board[right] !== 0 && board[left] > board[right]) inversions++; } } const blankRowFromBottom = WIDTH - rowOf(blank); return (inversions + blankRowFromBottom) % 2 === 1; } Add linear conflict to Manhattan distance
Manhattan distance adds the row and column distances from each numbered tile to its goal. A tile one row up and three columns left of its destination needs at least four moves. Adding those distances gives a lower bound because a legal move advances one tile by one square.
Now consider two tiles that are already in their goal row, in reversed order. To pass each other, at least one must leave the row and return. These two vertical moves are extra because that tile's vertical Manhattan distance was zero. The same argument for a column gives extra horizontal moves. Hansson, Mayer, and Yung's linear-conflict paper
Counting every inverted pair can charge the same detour more than once. In this example, take each row's tiles that belong in that row and read their goal columns from left to right. The ones that stay in the row for the entire solution must form an increasing subsequence. If the sequence is [3, 2, 1], at most one tile can stay, so at least two need a round trip. That's four extra moves. Column conflicts use the same rule in the other axis, so the two charges count distinct moves.
function minimumDepartures(goalPositions) { // Every line has at most four tiles, so a quadratic LIS is small. const lengths = Array(goalPositions.length).fill(1); let longest = 0; for (let end = 0; end < goalPositions.length; end++) { for (let before = 0; before < end; before++) { if (goalPositions[before] < goalPositions[end]) { lengths[end] = Math.max(lengths[end], lengths[before] + 1); } } longest = Math.max(longest, lengths[end]); } return goalPositions.length - longest; } function estimate(board) { const rows = Array.from({ length: WIDTH }, () => []); const columns = Array.from({ length: WIDTH }, () => []); let manhattan = 0; for (let index = 0; index < board.length; index++) { const tile = board[index]; if (tile === 0) continue; const row = rowOf(index); const column = columnOf(index); const goalRow = rowOf(tile - 1); const goalColumn = columnOf(tile - 1); manhattan += Math.abs(row - goalRow) + Math.abs(column - goalColumn); if (row === goalRow) rows[row].push(goalColumn); if (column === goalColumn) columns[column].push(goalRow); } let departures = 0; for (const line of [...rows, ...columns]) { departures += minimumDepartures(line); } return manhattan + 2 * departures; } Run IDA* one state at a time
IDA* runs depth-first search with a bound on f = g + h. Here g is the number of slides already made and h is the lower bound from estimate. Start with the initial board's h. When f exceeds the bound, prune that branch and remember its score. If a pass finishes without a solution, restart on the smallest score that exceeded the bound.
That choice of next bound preserves optimality. Along an optimal route, every f is at most the route's total length. An iteration therefore cannot skip the optimal length, and the first reached goal has the shortest possible move count. Skipping the immediate reversal is safe because a shortest route never spends two moves undoing itself. Korf's original IDA* paper
A generator lets the browser resume the exact point where search paused. The outer generator owns one mutable copy of the board, and each recursive generator yields before scoring a state. A finally block reverses each trial slide when the branch ends or when the caller closes the generator.
const neighbors = Array.from({ length: SIZE }, (_, index) => { const adjacent = []; if (rowOf(index) > 0) adjacent.push(index - WIDTH); if (rowOf(index) < WIDTH - 1) adjacent.push(index + WIDTH); if (columnOf(index) > 0) adjacent.push(index - 1); if (columnOf(index) < WIDTH - 1) adjacent.push(index + 1); return adjacent; }); function slide(board, blank, nextBlank) { board[blank] = board[nextBlank]; board[nextBlank] = 0; } function* search15(input) { const board = readBoard(input); const startBlank = board.indexOf(0); if (!isSolvable(board, startBlank)) return { status: "unsolvable" }; const moves = []; let bound = estimate(board); let nextBound = Infinity; function* visit(blank, previousBlank) { yield bound; const remaining = estimate(board); const score = moves.length + remaining; if (score > bound) { nextBound = Math.min(nextBound, score); return null; } if (remaining === 0) return moves.slice(); for (const nextBlank of neighbors[blank]) { if (nextBlank === previousBlank) continue; moves.push(board[nextBlank]); slide(board, blank, nextBlank); try { const answer = yield* visit(nextBlank, blank); if (answer !== null) return answer; } finally { slide(board, nextBlank, blank); moves.pop(); } } return null; } while (true) { const answer = yield* visit(startBlank, -1); if (answer !== null) return { status: "solved", moves: answer }; if (!Number.isFinite(nextBound)) { throw new Error("Search ran out of states for a reachable board"); } bound = nextBound; nextBound = Infinity; } } Give the browser time to handle input
The driver below advances the generator for about six milliseconds at a time, then waits for a timer task. Between slices the browser gets a chance to paint and handle clicks. An already-resolved promise only schedules a microtask, which can keep the browser in the same rendering turn. Six milliseconds is a starting budget. The browser can delay timers, so a slice and the overall deadline are cooperative limits. HTML event loop and timers
async function solve15( board, { signal, timeLimitMs = 5_000, onProgress } = {}, ) { if (!Number.isFinite(timeLimitMs) || timeLimitMs <= 0) { throw new RangeError("timeLimitMs must be a positive, finite number"); } const search = search15(board); const deadline = performance.now() + timeLimitMs; try { while (true) { signal?.throwIfAborted(); const sliceEnd = performance.now() + 6; let step; do { if (performance.now() >= deadline) return { status: "timed-out" }; step = search.next(); if (step.done) return step.value; } while (performance.now() < sliceEnd); onProgress?.({ bound: step.value }); await new Promise(resolve => setTimeout(resolve, 0)); } } finally { search.return(); } } A Cancel button can call controller.abort() for the active solve. Catch AbortError in the UI if you're using the default abort reason. Show the current bound as a search status rather than a percentage. Different bounds can involve very different amounts of work. A timeout means the time limit was reached. Only a failed parity check means the goal is unreachable. DOM AbortSignal
Try it on three boards
(async () => { const goal = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0]; const top = goal.slice(0, 12); console.log(await solve15(goal)); // { status: "solved", moves: [] } console.log(await solve15([...top, 13, 0, 14, 15])); // { status: "solved", moves: [14, 15] } console.log(await solve15([...top, 13, 15, 14, 0])); // { status: "unsolvable" } })(); The solution is a list of tile values. To animate it, start from a fresh copy of the original board and slide each named tile into the current blank. If your game lets someone push several tiles along a line with one click, count each individual slide so the solver and the UI agree on move totals.
For a visual example of board input and playback, try the same two-move position in the Sliding Tile Puzzle solver. You can also play a fresh board on Sliding Tile Puzzle.
AI assisted with drafting this tutorial.