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.

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:
| Part | Meaning | On the grid below |
|---|---|---|
| States | Every situation you could be in | Which square you're on |
| Initial state | Where you start | S |
| Actions | What you can do from a state | Step up, down, left or right, not into a wall |
| Goal test | How you know you're done | Am I on G? |
| Path cost | What a solution costs | 1 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.
| Algorithm | Frontier | Takes out next |
|---|---|---|
| Breadth-first (BFS) | FIFO queue | The oldest state: a widening ring |
| Depth-first (DFS) | LIFO stack | The 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-first | Priority 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 |
- Expanded
- 164
- Path steps
- 20
- Path cost
- 32
| On this map | Expanded | Steps | Cost |
|---|---|---|---|
| Breadth-first | 164 | 20 | 32 |
| Depth-first | 63 | 62 | 62 |
| Uniform-cost | 158 | 22 | 22 |
| Greedy best-first | 30 | 20 | 32 |
| A* | 74 | 22 | 22 |
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.
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) cheapestThe 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? | Time | Memory | |
|---|---|---|---|---|
| Breadth-first | Yes | If steps cost the same | O(b^d) | O(b^d) |
| Uniform-cost | Yes | Yes | O(b^(1+C*/ε)) | Same as time |
| Depth-first | Not if paths are infinite | No | O(b^m) | O(bm) |
| Depth-limited | Only if goal ≤ L deep | No | O(b^L) | O(bL) |
| Iterative deepening | Yes | If steps cost the same | O(b^d) | O(bd) |
| Greedy best-first | Not always | No | Depends on h | Depends on h |
| A* | Yes | Yes, with admissible h | Depends on h | Keeps 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 answerHide the answer
02Why is Manhattan distance admissible on the grid but straight-line distance a weaker heuristic?
Show the answerHide the answer
03You're writing a web crawler that should find pages close to the home page first. Which search?
Show the answerHide the answer
04Find a map in the grid where greedy best-first returns a more expensive path than A*.
Show the answerHide the answer
Further reading
- Red Blob Games: Introduction to A* ↗
The best explanation of this material anywhere, with diagrams you can drag. This lesson's grid is a tribute to it.
- Artificial Intelligence: A Modern Approach, chapter 3 ↗
The formal definitions, proofs of when each search is complete and optimal, and the iterative-deepening numbers.
- A* search algorithm (Wikipedia) ↗
History back to Hart, Nilsson and Raphael's 1968 paper, plus admissibility and consistency.