AI from scratch · Elective · Search and planning

Search, planning and constraints

Before neural networks learned to approximate functions from data, artificial intelligence began with a clean mathematical question: if you have an exact model of the world, how do you find the best sequence of moves to reach a goal? This is search and planning — the foundation of route navigation, chess engines, robotics pathing, and modern chain-of-thought agent reasoning. In this lesson we build the classical algorithms of CS221: from breadth-first search and Dijkstra to A* on New York rail, minimax game search with α-β pruning, and constraint satisfaction for scheduling.

1. States, actions and costs: BFS vs Dijkstra

A search problem defines a state space (every situation the agent could be in), a start state, a set of actions available from each state, a transition model giving the resulting state, an action cost \(c(s, a)\), and a goal test. Together, these form a graph: states are nodes, actions are edges connecting them, and reachable states are neighbors.

The map below is a simplified sketch built from real station names: positions are roughly to scale, minutes are round numbers, Grand Central–Penn Station is a crosstown subway transfer, and two links (Woodside–New Rochelle, White Plains–Stamford) don't exist as passenger rail. They're there to give the search real choices.

The simplest search is Breadth-First Search (BFS): it explores outward level by level using a first-in, first-out (FIFO) queue. BFS finds the path with the fewest hops. But real actions take different amounts of time or fuel. When step costs differ, BFS fails to find the cheapest route: a 3-hop journey taking 60 minutes will be picked over a 4-hop journey taking 56 minutes.

Uniform-Cost Search (UCS), also known as Dijkstra's algorithm, fixes this by prioritizing cumulative cost \(g(s)\) from the start using a priority queue (Python's heapq). It always expands the frontier node with the lowest total travel cost so far.

unvisited frontier (queue) expanded optimal path

Click Run to watch the search navigate from Grand Central to Stamford.

Breadth-First Search finds the path with the fewest hops; Uniform-Cost Search finds the lowest cumulative cost using a priority queue.

2. A* search: guiding the search with heuristics

Dijkstra expands blindly in all directions like ripples in a pond: heading toward Connecticut, it still expands Long Island stations (Jamaica, Mineola, Hicksville) simply because their cumulative minutes are small. To guide search toward the goal, we add a heuristic \(h(s)\): an estimate of the remaining cost from state \(s\) to the goal.

A* search evaluates each node by the sum:

\[ f(s) = g(s) + h(s) \]

where \(g(s)\) is the exact cost incurred so far, and \(h(s)\) is the estimated cost to go. The priority queue always pops the state with smallest \(f(s)\).

A heuristic is admissible if it never overestimates the true remaining cost: \(h(s) \le h^*(s)\) for every state \(s\). On maps, straight-line Euclidean distance divided by the train's maximum speed is always admissible: no track can be shorter than a straight line, and no train can exceed its top speed.

A destination is 30 miles away in a straight line. If the maximum possible train speed on any track is 60 mph (1 mile per minute), what is the maximum admissible heuristic \(h\) in minutes?

\(30\text{ miles} \div 1\text{ mile/min} = 30\text{ minutes}\). If you guessed 35 minutes, you might overestimate if a direct high-speed line existed, which would break the admissibility guarantee.

Look at the canvas above when you switch the algorithm to A* Search: Dijkstra expanded almost every station, out to Long Island,, whereas A* focused immediately along the Sound corridor to Stamford, expanding only 5 stations!

A* prioritizes \(f(s) = g(s) + h(s)\); if \(h(s)\) never overestimates (admissible), A* finds the optimal path while exploring far fewer states.

Why an admissible heuristic guarantees the shortest path
  1. Suppose A* is about to pop a suboptimal goal node \(G_2\) from the queue with cost \(g(G_2) > C^*\), where \(C^*\) is the true optimal cost.
  2. Because the true optimal path to the best goal \(G^*\) has not been completed yet, there must be at least one unexpanded ancestor node \(n\) along that optimal path currently waiting in the priority queue.
  3. Since the heuristic is admissible (\(h(n) \le h^*(n)\)), its evaluation score satisfies:
    \[ f(n) = g(n) + h(n) \le g(n) + h^*(n) = C^* \]
  4. At the goal node \(G_2\), the remaining cost is zero (\(h(G_2) = 0\)), so \(f(G_2) = g(G_2) > C^*\).
  5. Combining these inequalities: \(f(n) \le C^* < f(G_2)\). Because the priority queue always pops the node with the lowest \(f\), it will pop \(n\) before \(G_2\)!
  6. Therefore, A* cannot terminate on a suboptimal goal while an optimal route remains unexplored.

3. Adversarial search: Minimax and α-β pruning

When another agent acts against you in a zero-sum game, you cannot plan a fixed sequence of moves; you must plan for their best responses. This is adversarial search. One player is MAX (trying to maximize the utility score), and the other is MIN (trying to minimize it).

The Minimax value of a state is defined recursively:

\[ V(s) = \begin{cases} \text{Utility}(s) & \text{if } \text{IsTerminal}(s) \\ \max_{a \in A(s)} V(\text{Result}(s, a)) & \text{if } \text{Player}(s) = \text{MAX} \\ \min_{a \in A(s)} V(\text{Result}(s, a)) & \text{if } \text{Player}(s) = \text{MIN} \end{cases} \]

Plain minimax visits every leaf in the game tree: for branching factor \(b\) and depth \(d\), it checks \(O(b^d)\) positions. But we can skip whole branches that cannot affect the decision. This is α-β pruning:

Whenever \(\beta \le \alpha\), MIN already has a move that keeps the score at or below \(\beta\), while MAX already has a better alternative elsewhere worth at least \(\alpha\). MAX will never allow the game to enter this subtree, so we can prune (cut off) the remaining children immediately.

α-β: 5 leaves evaluated, 3 pruned, same move. Leaf 9 is skipped because that MAX node already has 6 and the MIN above it already has 5; R2 is skipped because R is already ≤ 2 and MAX already has 5.

Why does α-β pruning never change the move that Minimax chooses?

If \(\beta \le \alpha\), the parent node will never be chosen by rational players regardless of what unknown values lie deeper in the pruned branch.

Minimax plans against an adversary; α-β pruning skips branches that cannot change the outcome, at best cutting the effective branching factor from \(b\) to about \(\sqrt b\), so the same time searches twice as deep.

4. Constraint satisfaction: Backtracking and forward checking

In standard search, we look for a sequence of actions. In a Constraint Satisfaction Problem (CSP), the state is factored into a set of variables \(X = \{X_1, X_2, \dots, X_n\}\), each with a domain of allowed values \(D_i\), and a set of constraints specifying which combinations of assignments are legal. The goal is simply to find any complete, consistent assignment.

Consider scheduling overnight track maintenance across four interconnected rail lines: Hudson (\(H\)), Harlem (\(M\)), New Haven (\(N\)), and LIRR (\(L\)). Available shifts are Nights \(\{1, 2, 3\}\). Lines that share junction trackage or maintenance crews cannot be serviced on the same night: \(H \ne M\), \(M \ne N\), \(H \ne N\), and \(M \ne L\).

Brute-force testing all \(3^4 = 81\) combinations is wasteful. Backtracking search assigns one variable at a time, checking consistency after each assignment. Adding forward checking makes it much smarter: whenever variable \(X\) is assigned, it immediately filters the domains of all unassigned neighbors, removing values that conflict. If any variable's domain becomes empty, it backtracks immediately before wasting work on a doomed subtree.

CSPs represent problems as variables, domains, and constraints; backtracking with forward checking prunes dead ends early by tracking remaining legal values.

Where it breaks: state explosions, bad heuristics, and world mismatch

5. What to carry forward

All lessons: AI from scratch. The rail network here is a simplified sketch (section 1), not a timetable. Core curriculum reference: Stanford CS221 (Artificial Intelligence: Principles and Techniques).

Last updated