Skip to content
← Notes

Lesson 06 · Artificial intelligence · 15 min

Search: finding a way

BFS, DFS, uniform-cost, greedy and A* on a map you can draw on. The same loop each time; only the order of the frontier changes.

My handwritten notes: Search, search space, and uninformed versus informed techniques

After this you can

  • Describe any search problem as states, actions, a goal test and costs
  • Implement BFS, DFS, uniform-cost, greedy and A* from one template
  • Pick the right search for a problem, and say what it costs in time and memory

My page opens with a definition I still like: search is the systematic examination of states to find a path from the start state to the goal state. The set of possible states, together with the operators that connect them, is the search space. A solution is a path from the initial state to a state that passes the goal test.

Then it splits the techniques in two. Uninformed searches know nothing beyond the problem definition: breadth-first, uniform-cost, depth-first, depth-limited and iterative deepening. Informed (heuristic) searches have some way to tell whether one state looks more promising than another. This lesson covers all of them with one loop and one map.

Writing a problem down

Before any algorithm, a search problem needs five things:

PartMeaningOn the grid below
StatesEvery situation you could be inWhich square you're on
Initial stateWhere you startS
ActionsWhat you can do from a stateStep up, down, left or right, not into a wall
Goal testHow you know you're doneAm I on G?
Path costWhat a solution costs1 per open square, 5 per mud square

The same five parts describe a route across Kumasi, a Rubik's cube, a timetable or a chess position. Once a problem is written this way, any algorithm below can solve it, and none of them needs to know what the states mean.

One loop, five algorithms

Every search on my page runs the same loop. Keep a frontier of states you've discovered but not explored yet. Take one out, check whether it's the goal, and add its neighbours to the frontier. Leave a breadcrumb at each new state saying where you came from, so you can trace the path back at the end.

The algorithms differ in one thing only: which state comes out of the frontier next. My page notes that BFS uses a FIFO queue, and in the corner I wrote FIFO and LIFO next to “data structures.” That's the whole idea.

AlgorithmFrontierTakes out next
Breadth-first (BFS)FIFO queueThe oldest state: a widening ring
Depth-first (DFS)LIFO stackThe newest state: down one corridor as far as it goes
Uniform-cost (UCS)Priority queue by g(n)The cheapest to reach so far (this is Dijkstra's algorithm)
Greedy best-firstPriority queue by h(n)The one that looks closest to the goal
A*Priority queue by g(n) + h(n)The best estimated total: cost so far plus estimate to go
SG
Expanded
164
Path steps
20
Path cost
32
frontier expanded
On this mapExpandedStepsCost
Breadth-first1642032
Depth-first636262
Uniform-cost1582222
Greedy best-first302032
A*742222
Drag across the grid to draw walls or mud. Drag S or G to move them. Mud costs 5 to cross, open ground costs 1.

Some things to try on the map:

  • Watch BFS spread in a ring, then compare its path cost with UCS. BFS finds the fewest steps, straight through the mud. UCS finds the cheapest route, around it.
  • Run DFS. It finds a path, often a ridiculous one, because it never asks whether there's a better one.
  • Greedy rushes at the goal and expands very little, but can be fooled. Draw a wall shaped like a cup facing S and watch it walk into the cup.
  • A* expands far less than UCS and still finds the cheapest path. That's the point of it.
search.py: every strategy from one looppython
import heapqfrom collections import dequedef search(start, goal, neighbours, strategy, h=lambda n: 0):    """One loop for every strategy. Only the frontier changes."""    came_from = {start: None}          # breadcrumbs back to the start    cost = {start: 0}                  # g(n): the cheapest cost found so far    if strategy == "bfs":              # FIFO queue: oldest first        frontier = deque([start])        pop, push = frontier.popleft, frontier.append    elif strategy == "dfs":            # LIFO stack: newest first        frontier = [start]        pop, push = frontier.pop, frontier.append    else:                              # priority queue: lowest score first        score = {"ucs": lambda n: cost[n],                 "greedy": lambda n: h(n),                 "astar": lambda n: cost[n] + h(n)}[strategy]        frontier = [(0, start)]        pop = lambda: heapq.heappop(frontier)[1]        push = lambda n: heapq.heappush(frontier, (score(n), n))    while frontier:        node = pop()        if node == goal:            break        for nxt, step in neighbours(node):            new = cost[node] + step            if nxt not in cost or (strategy in ("ucs", "astar") and new < cost[nxt]):                cost[nxt] = new                came_from[nxt] = node                push(nxt)    path, node = [], goal    while node is not None:            # follow the breadcrumbs home        path.append(node)        node = came_from.get(node)    return path[::-1], cost.get(goal)# A small map. Each road's cost is minutes of driving.roads = {    "Home":     [("Junction", 4), ("Market", 2)],    "Market":   [("Junction", 5), ("Bridge", 10)],    "Junction": [("Bridge", 3), ("Campus", 12)],    "Bridge":   [("Campus", 4)],    "Campus":   [],}for strategy in ["bfs", "dfs", "ucs"]:    print(strategy, search("Home", "Campus", roads.get, strategy))# bfs (['Home', 'Junction', 'Campus'], 16)            fewest roads# dfs (['Home', 'Market', 'Bridge', 'Campus'], 16)    whatever it hit first# ucs (['Home', 'Junction', 'Bridge', 'Campus'], 11)  cheapest

The heap is the binary heap from the tree lesson, stored in an array with children at 2i and 2i + 1. It hands back the lowest score in O(log n).

The uninformed ones, one by one

Breadth-first expands everything at depth 1, then everything at depth 2, and so on: the root first, then all its successors, then theirs, exactly as my page puts it. It always finds the shallowest goal, which is the cheapest one when every step costs the same. Its problem is memory. With b choices per state and the goal at depth d, it holds about b^d states at once. With 10 choices and depth 8 that's a hundred million.

Uniform-cost is breadth-first for unequal costs: always expand the cheapest state found so far. On a road map, that's Dijkstra's algorithm from 1959, which still runs inside internet routers today (OSPF stands for Open Shortest Path First).

Depth-first needs very little memory, only the current path and its siblings, but it can wander forever down an infinite branch, and the first path it finds is rarely the best.

Depth-limited is DFS with a cut-off: don't go deeper than L. It can't loop forever, but if the goal is deeper than L it won't find it.

Iterative deepening runs depth-limited search with L = 0, 1, 2, 3… until it finds the goal. It looks wasteful, since it re-explores the top levels every time, but most of a tree is in its bottom level. With 10 choices per state and the goal at depth 5, BFS generates 111,110 states and iterative deepening 123,450, about 11% more. For that it gets BFS's guarantees with DFS's memory. When the search space is big and you don't know how deep the answer is, this is usually the uninformed method to pick.

Informed search: a hint about where to go

A heuristic h(n) estimates the cost from state n to the goal. On the grid it's the Manhattan distance: squares across plus squares down, ignoring walls. Greedy best-first trusts the estimate completely, and it's fast until it's wrong. A* adds the estimate to the real cost so far, f(n) = g(n) + h(n), and only expands where the total looks good.

A* is guaranteed to find the cheapest path if the heuristic is admissible: it never overestimates. Manhattan distance can't, because you can't reach G in fewer steps than that even with no walls and no mud. Make the heuristic too large and A* gets faster but starts returning worse paths. That's a real trade-off games make deliberately.

Finds a path?Cheapest?TimeMemory
Breadth-firstYesIf steps cost the sameO(b^d)O(b^d)
Uniform-costYesYesO(b^(1+C*/ε))Same as time
Depth-firstNot if paths are infiniteNoO(b^m)O(bm)
Depth-limitedOnly if goal ≤ L deepNoO(b^L)O(bL)
Iterative deepeningYesIf steps cost the sameO(b^d)O(bd)
Greedy best-firstNot alwaysNoDepends on hDepends on h
A*YesYes, with admissible hDepends on hKeeps every frontier state

b: choices per state. d: depth of the shallowest goal. m: the deepest any path goes. C*: the cheapest solution's cost. ε: the smallest step cost.

Where you'll meet these

  • Maps and games

    Route planners and game characters use A* and faster descendants of Dijkstra's algorithm, with heuristics tuned to the map.

  • Networks

    Routers compute shortest paths with Dijkstra (OSPF). “Degrees of separation” on a social network is a BFS.

  • Your tools

    Garbage collectors walk the graph of live objects from the roots. Package managers search for a set of versions that satisfies every dependency.

  • Puzzles and planning

    Sudoku, timetables, delivery rounds: search with backtracking, like the timetable in the AI lesson.

Try it

01On the small road map in the code, what does A* return if h is zero everywhere?

Show the answer
The same as UCS, Home → Junction → Bridge → Campus at 11 minutes. With h = 0, g + h is just g. A* is UCS plus a hint.

02Why is Manhattan distance admissible on the grid but straight-line distance a weaker heuristic?

Show the answer
Both never overestimate, since you can only move in four directions. Manhattan is always at least as large as straight-line, so it's a tighter, more informed estimate, and A* expands fewer states with it.

03You're writing a web crawler that should find pages close to the home page first. Which search?

Show the answer
Breadth-first, with the frontier as a queue of URLs and a set of seen URLs so you don't fetch a page twice.

04Find a map in the grid where greedy best-first returns a more expensive path than A*.

Show the answer
The starting map already is one: the mud sits right on the straight line from S to G. Greedy follows its estimate into the mud and pays 5 a square; A* weighs the real cost and goes around. Compare the cost column in the table.

Further reading

07 · Contact

Write to me.

I'm open to software engineering and data roles, and to freelance work. If you have a process that still runs on copy and paste, I'd like to hear about it.