AlgoTales · Roadmap

State-space search

Advanced · 10 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

State-space search treats every possible situation of a puzzle or process as a "state" and every legal move as a connection to another state, then explores outward to find the shortest way from start to goal. It solves puzzles by exploring moves level by level.

Practical use cases

  • Web app: Word ladder game. A word-game site asks players to change COLD to WARM one letter at a time, with each step a real word. Treating each word as a state and one-letter changes as moves, a search level by level finds the shortest ladder, so the hint button works instantly.
  • Web app: Sliding-tile puzzle hint button. A browser puzzle shows the next best move. The solver explores arrangements one slide away, then two, and so on, until it reaches the solved board, and then reports the shortest sequence. Players get a real shortest answer, and the hint button reacts instantly for small boards.
  • Web app: Lock or PIN combination planner. A testing tool must find the fewest dial turns to reach a target code while avoiding forbidden codes. Each code is a state and each turn a move, so a level-by-level search gives the fewest turns. The tool reports the fewest turns, and never repeats a combination it has already tried.
  • System: Gene mutation and game AI. Biology tools count the fewest valid single changes to turn one gene string into another, and game AI explores possible positions after each move to pick a good line. Each position is visited once, so the answer is found without trying endless random moves.

The story: The Word Ladder Game

At the school fair, Aarav’s stall had a word game: "Turn HIT into COG. Change one letter at a time, and every step must be a real word. Fewest steps wins a laddoo!" Kabir tried HIT → HOT → DOT → DOG → COG on his first go. Zoya tried HIT → HOT → LOT → LOG → COG. Both four moves. Could anyone do it in three?

Mira saw the game differently: each word is a place, and each one-letter change is a road to a neighbouring word. The "map" is hidden, but you can always list the neighbours of any word. Now the puzzle is just: find the shortest way from HIT to COG on this map.

Fewest steps means exploring ring by ring: first everything one move away, then two moves, then three. Put the words in a queue (first in, first out), take one, add its unseen neighbours at the back, and remember which word you came from. The moment COG shows up, it is the shortest.

This is state-space search: any puzzle where a situation (a word, a sliding-puzzle board, a lock combination) can turn into other situations by legal moves. The smell: "minimum number of moves/steps/mutations", "transform A into B", "puzzle", "lock", "gene change". Model it as a graph you build as you go, and use BFS.

How to spot this problem, and where you need it

You want the fewest moves, steps or changes to get from a starting situation to a goal situation, where each move changes things a little and some moves are forbidden.

Signs you need it

  • The problem says "minimum number of moves/steps/turns/mutations" to reach a target, with rules for what a single step may do.
  • You can describe the whole situation as one value, such as a string, a board layout or a set of numbers.
  • Each situation leads to a small number of next situations, and many of them repeat.

Where to use it in a project

  • Puzzle and word games with a hint or solve button.
  • Planning tools for lock codes, configurations or step-by-step workflows.
  • Game AI and move planners that explore positions after each move.

The solution

Describe each situation as a state you can store (a string or a tuple). Put the start in a queue and in a visited set. Repeatedly take a state, generate all states one legal move away, and add the unvisited ones to the queue with one more step counted. Because the queue handles states in order of distance, the first time you reach the goal is the fewest-moves answer.

Payoff: Before: guessing move sequences at random, or trying every path. After: the shortest answer found by visiting each state only once.

Explain it like I am 8

In a sliding-tile puzzle, every arrangement of tiles is a "state", and every legal slide takes you to a different state. To find the fewest slides, try all arrangements one slide away, then all two slides away, and so on. The first time you see the solved picture, you stop.

How it works, step by step

  1. Spot the clue: "minimum number of moves/steps" to turn one situation into another by legal moves.
  2. Define a state (a word, a board, a combination) and a neighbours function that lists legal next states.
  3. BFS with a queue: start with the start state at distance 0, and keep a seen set so no state is queued twice.
  4. Pop a state, generate neighbours, and push each unseen one with distance + 1 (and remember its parent if you need the path).
  5. Stop at the goal. BFS reaches it in the fewest moves. If the queue empties first, the goal is unreachable.

The code in four languages

PHP

<?php
// Classic: "Word Ladder": the fewest one-letter changes from start to goal.
function ladderMoves(string $start, string $goal, array $words): int {
    $valid = array_flip($words);                  // fast "is this a real word?" lookup
    $queue = [[$start, 0]];                       // state = word, plus its distance
    $seen = [$start => true];
    for ($head = 0; $head < count($queue); $head++) {
        [$word, $moves] = $queue[$head];
        if ($word === $goal) return $moves;       // BFS: first arrival is the shortest
        for ($i = 0; $i < strlen($word); $i++) {
            foreach (range('a', 'z') as $ch) {    // every possible single-letter change
                $next = $word;
                $next[$i] = $ch;
                if (isset($valid[$next]) && !isset($seen[$next])) {
                    $seen[$next] = true;
                    $queue[] = [$next, $moves + 1];
                }
            }
        }
    }
    return -1;                                    // goal unreachable
}
$dictionary = ['hot', 'dot', 'dog', 'cog', 'lot', 'log'];
echo ladderMoves('hit', 'cog', $dictionary), "
";                          // 4
echo ladderMoves('hit', 'cog', ['hot', 'dot', 'dog', 'lot', 'log']), "
";   // -1  (cog missing)

JavaScript

// Classic: "Word Ladder": the fewest one-letter changes from start to goal.
function ladderMoves(start, goal, words) {
  const valid = new Set(words);                 // fast "is this a real word?" lookup
  const queue = [[start, 0]];                   // state = word, plus its distance
  const seen = new Set([start]);
  for (let head = 0; head < queue.length; head++) {
    const [word, moves] = queue[head];
    if (word === goal) return moves;            // BFS: first arrival is the shortest
    for (let i = 0; i < word.length; i++) {
      for (let c = 97; c <= 122; c++) {         // every possible single-letter change
        const next = word.slice(0, i) + String.fromCharCode(c) + word.slice(i + 1);
        if (valid.has(next) && !seen.has(next)) {
          seen.add(next);
          queue.push([next, moves + 1]);
        }
      }
    }
  }
  return -1;                                    // goal unreachable
}
const dictionary = ['hot', 'dot', 'dog', 'cog', 'lot', 'log'];
console.log(ladderMoves('hit', 'cog', dictionary));                          // 4
console.log(ladderMoves('hit', 'cog', ['hot', 'dot', 'dog', 'lot', 'log']));  // -1  (cog missing)

Java

import java.util.*;

public class Main {
    // Classic: "Word Ladder": the fewest one-letter changes from start to goal.
    record State(String word, int moves) {}

    static int ladderMoves(String start, String goal, List<String> words) {
        Set<String> valid = new HashSet<>(words);          // fast "is this a real word?" lookup
        Deque<State> queue = new ArrayDeque<>();
        queue.add(new State(start, 0));                    // state = word, plus its distance
        Set<String> seen = new HashSet<>(List.of(start));
        while (!queue.isEmpty()) {
            State cur = queue.poll();
            if (cur.word().equals(goal)) return cur.moves();   // BFS: first arrival is the shortest
            for (int i = 0; i < cur.word().length(); i++) {
                for (char ch = 'a'; ch <= 'z'; ch++) {         // every possible single-letter change
                    String next = cur.word().substring(0, i) + ch + cur.word().substring(i + 1);
                    if (valid.contains(next) && !seen.contains(next)) {
                        seen.add(next);
                        queue.add(new State(next, cur.moves() + 1));
                    }
                }
            }
        }
        return -1;                                         // goal unreachable
    }

    public static void main(String[] args) {
        List<String> dictionary = List.of("hot", "dot", "dog", "cog", "lot", "log");
        System.out.println(ladderMoves("hit", "cog", dictionary));                                // 4
        System.out.println(ladderMoves("hit", "cog", List.of("hot", "dot", "dog", "lot", "log")));  // -1  (cog missing)
    }
}

Go

package main

import "fmt"

// state is a word plus its distance from the start.
type state struct {
	word  string
	moves int
}

// ladderMoves is "Word Ladder": the fewest one-letter changes from start to goal.
func ladderMoves(start, goal string, words []string) int {
	valid := map[string]bool{} // fast "is this a real word?" lookup
	for _, w := range words {
		valid[w] = true
	}
	queue := []state{{start, 0}} // state = word, plus its distance
	seen := map[string]bool{start: true}
	for head := 0; head < len(queue); head++ {
		cur := queue[head]
		if cur.word == goal {
			return cur.moves // BFS: first arrival is the shortest
		}
		for i := 0; i < len(cur.word); i++ {
			for ch := byte('a'); ch <= 'z'; ch++ { // every possible single-letter change
				next := cur.word[:i] + string(ch) + cur.word[i+1:]
				if valid[next] && !seen[next] {
					seen[next] = true
					queue = append(queue, state{next, cur.moves + 1})
				}
			}
		}
	}
	return -1 // goal unreachable
}

func main() {
	dictionary := []string{"hot", "dot", "dog", "cog", "lot", "log"}
	fmt.Println(ladderMoves("hit", "cog", dictionary))                                  // 4
	fmt.Println(ladderMoves("hit", "cog", []string{"hot", "dot", "dog", "lot", "log"})) // -1  (cog missing)
}

Time: O(words × length × 26) · Extra space: O(words). Each word is queued once, and for each we try 26 letters at every position.

Watch out for

  • Using DFS and expecting the shortest answer. Only BFS (ring by ring) guarantees fewest moves in an unweighted state graph.
  • Forgetting the seen set, so states are re-queued and the search explodes or loops forever.
  • Marking a state as seen only when popping, not when queueing, which fills the queue with duplicates.

Quick check

  1. Which clue points to state-space search?
    • "merge overlapping intervals"
    • "count ones in a binary number"
    • "sum of nested lists"
    • "minimum moves to transform one configuration into another"
  2. Why BFS and not DFS for the fewest moves?
    • BFS uses less memory
    • DFS cannot use a queue
    • BFS explores ring by ring, so the first arrival is the shortest
    • DFS cannot visit all states
  3. What are the "states" in the word ladder?
    • The words themselves
    • The letters
    • The queue
    • The dictionary file