AI Search Algorithms Explained with Pac-Man
On this page

Few university projects were as much fun as building agents for Pac-Man with a team of four. The agent had to navigate a maze, eat all the food efficiently and stay away from the ghosts. It sounds like a game; it is actually a full tour of classical AI — search, heuristics, adversarial reasoning and reinforcement learning.
To make the search part visible, I ran four algorithms on the same maze. The picture above shows which cells each one explored before it reached the goal, and the numbers tell the story better than any definition.
Every search is the same loop
The most important idea first: BFS, DFS, UCS and A* are all the same algorithm. The only difference is which node from the frontier is expanded next. Here is the generic graph search:
def graph_search(problem, frontier):
frontier.push((problem.start, [], 0)) # (state, path, cost so far)
explored = set()
while not frontier.is_empty():
state, path, cost = frontier.pop()
if problem.is_goal(state):
return path
if state in explored:
continue
explored.add(state)
for nxt, action, step in problem.successors(state):
if nxt not in explored:
frontier.push((nxt, path + [action], cost + step))
return None
Change the data structure behind frontier, and you get a different algorithm:
dfs = lambda p: graph_search(p, Stack())
bfs = lambda p: graph_search(p, Queue())
ucs = lambda p: graph_search(p, PriorityQueueWithFunction(lambda n: n[2]))
astar = lambda p, h: graph_search(p, PriorityQueueWithFunction(lambda n: n[2] + h(n[0], p)))
What the experiment shows
I ran exactly this code on the maze in the picture at the top. The yellow area is a “ghost zone” where every step costs 5 instead of 1. These are the results:
| Algorithm | Nodes expanded | Path cost | Optimal? |
|---|---|---|---|
| DFS | 106 | 60 | ❌ |
| BFS | 134 | 56 | ✅ (here, because it avoided the costly zone by luck of the maze) |
| UCS | 117 | 56 | ✅ |
| A* (Manhattan distance) | 87 | 56 | ✅ |
A few things stand out:
- DFS dives deep in one direction and returns the first path it finds — here 4 steps longer than needed.
- BFS finds the path with the fewest steps, but it ignores step costs, so it happily explores inside the costly ghost zone.
- UCS always expands the cheapest path so far, so it is optimal even with different costs.
- A* finds the same optimal path as UCS while expanding the fewest nodes, because the heuristic guides it toward the goal. Look at the bottom-right picture: most of the maze stays white (unexplored).
Heuristics: the hard part
A* is only as good as its heuristic h(n) — the estimate of the remaining cost to the goal. Two properties matter:
| Property | Meaning | Guarantee |
|---|---|---|
| Admissible | Never overestimates: h(n) ≤ real cost |
A* finds the optimal path |
| Consistent | h(n) ≤ step(n → n') + h(n') |
A* graph search stays optimal and never re-opens nodes |
h = 0 |
Admissible, but gives no information | A* becomes UCS |
For a grid without diagonal moves, Manhattan distance is admissible:
def manhattan(state, problem):
(x1, y1), (x2, y2) = state, problem.goal
return abs(x1 - x2) + abs(y1 - y2)
From the project: In the food-eating part of the project, “distance to the nearest food” is admissible but weak. “Distance to the farthest food” is still admissible — Pac-Man has to reach it eventually — and much stronger. The best heuristic is the tightest estimate that still never overestimates.
Adversarial search: when the ghosts fight back
The maze doesn’t move, but ghosts do. Now Pac-Man has to think about what the ghosts will do, and we are searching a game tree:
def minimax(state, depth, agent):
if depth == 0 or state.is_terminal():
return evaluate(state)
nxt = (agent + 1) % state.num_agents
d = depth - 1 if nxt == 0 else depth # one ply = every agent moved once
scores = [minimax(state.after(agent, a), d, nxt) for a in state.legal_actions(agent)]
return max(scores) if agent == 0 else min(scores) # Pac-Man maximizes, ghosts minimize
There are three versions worth knowing:
- Minimax — assumes the ghosts play perfectly against you. Safe, but very cautious.
- Alpha-beta pruning — the same result as minimax, but it skips branches that cannot change the decision. In the tree above, once the right MIN node sees the value 2, it is already worse than the 3 that MAX has, so the leaf 9 is never evaluated.
- Expectimax — assumes the ghosts move randomly and uses the average. Real ghosts are not perfect, so expectimax makes Pac-Man braver — and it usually scores more against them.
Reinforcement learning: learning without a map
In the last part of the project, Pac-Man had no model of the maze at all. It plays, receives rewards (for example +10 for food, +500 for winning, −500 for being caught), and learns a value for each state and action. This is Q-learning, and the whole algorithm is one line:
Q[s][a] += alpha * (reward + gamma * max(Q[s2].values()) - Q[s][a])
| Parameter | What it controls | Typical value |
|---|---|---|
alpha (learning rate) |
How fast new experience replaces old knowledge | 0.2–0.5 |
gamma (discount) |
How much future rewards matter | 0.8–0.99 |
epsilon (exploration) |
Chance of a random move instead of the best known one | Start high, decay to ~0.05 |
On a big maze, a table with a value for every state is too large. Approximate Q-learning solves this by learning weights for features (distance to the nearest food, ghosts one step away, …) instead of every state — the same idea that later grew into deep reinforcement learning.
One loop, many algorithms
Classical AI search is one loop where the frontier decides everything: a stack gives DFS, a queue gives BFS, a priority queue on cost gives UCS, and adding a heuristic gives A. With an admissible heuristic A stays optimal — and the experiment above shows how many nodes it saves. Add opponents and you need minimax with alpha-beta (or expectimax for imperfect ones); remove the model entirely and Q-learning learns from rewards. To try it yourself, start with the Pac-Man projects from UC Berkeley’s CS188.