Breadth-first and depth-first search
Uninformed search selects the next candidate without an estimate of how close it is to a goal. Breadth-first search (BFS) tries shallow routes first; depth-first search (DFS) follows a branch before trying alternatives. Neither learns from data. Both can solve the fictional room-routing problem from the previous chapter.
A small graph to search
Start at A and reach G. The directed corridors are A→B (2), A→C (2), A→G (9), B→A (2), B→D (1), C→G (2), and D→G (2). X is isolated. Numbers are energy units, not probabilities. Every destination is declared; empty dictionaries mean no exits. BFS and DFS ignore the weights. A path includes its start; depth counts edges, so [A] has depth zero.
BFS: visit the shallowest routes first
A FIFO queue removes the oldest waiting item. Python’s standard-library deque supports append at the right and popleft at the left. Store each path and mark a state as seen when enqueuing it. Since states are fully described by their room label, a later route to a seen state cannot improve its edge count. This avoids repeatedly following B→A.
from collections import deque
def bfs(graph, start, goal): frontier = deque([[start]]) seen = {start} while frontier: path = frontier.popleft() state = path[-1] if state == goal: return path for neighbor in graph[state]: if neighbor not in seen: seen.add(neighbor) frontier.append(path + [neighbor]) return None
graph = {"A": {"B": 2, "C": 2, "G": 9}, "B": {"A": 2, "D": 1}, "C": {"G": 2}, "D": {"G": 2}, "G": {}, "X": {}}print(bfs(graph, "A", "G"))print(bfs(graph, "A", "X"))The two lines are ['A', 'G'] and None. Initially the queue holds A. Removing A adds paths AB, AC and AG in that order. Removing AB adds ABD; removing AC cannot enqueue another G because G is already seen. Removing AG succeeds. G has depth 1, and no zero-edge route reaches G from A. If the frontier empties, no route exists in this finite graph. Starting at the goal returns the one-state path.
DFS: explore a branch before its siblings
A LIFO stack removes the newest item. Here we reverse the ordered neighbor list before pushing, so the first listed neighbor is visited first. Unlike the BFS code, DFS marks a state when it is popped and skips duplicate pending paths; this preserves the intended depth-first exploration order. A seen state never needs another expansion for simple reachability in this static graph.
def dfs(graph, start, goal): stack = [[start]] seen = set() while stack: path = stack.pop() state = path[-1] if state in seen: continue seen.add(state) if state == goal: return path for neighbor in reversed(list(graph[state])): if neighbor not in seen: stack.append(path + [neighbor]) return None
graph = {"A": {"B": 2, "C": 2, "G": 9}, "B": {"A": 2, "D": 1}, "C": {"G": 2}, "D": {"G": 2}, "G": {}, "X": {}}print(dfs(graph, "A", "G"))print(dfs(graph, "G", "G"))The first output is ['A', 'B', 'D', 'G'], the second ['G']. The stack initially receives AG, AC and AB; AB is popped first. B cannot revisit A, so D is next; D adds G and that path wins. DFS did not inspect the shorter pending AG route first. It finds a valid route but not necessarily a shortest one. Reordering neighbors may change which valid route DFS returns.
Completeness and memory
Completeness means finding a solution whenever one exists, given the stated assumptions; optimality means minimizing the objective. On a finite explicit graph, both implementations terminate and find a reachable goal. BFS minimizes edge count and also cost when all steps have the same nonnegative cost. DFS has no such general optimum guarantee. On an implicit infinite search tree, BFS reaches any finite-depth goal if branching is finite, but unbounded DFS can pursue an infinite branch forever. Cycle checks alone do not fix infinite acyclic branches.
Let V count states and E count directed edges. Ordinary adjacency-list BFS and DFS with parent pointers and suitable seen bookkeeping take O(V+E) time; BFS needs O(V) auxiliary state storage and DFS can use O(V) with a recursive or iterator-stack implementation. The simple DFS above may queue duplicate candidates, and both examples copy full paths; their actual storage and work can be larger than those standard bounds. In tree search with branching factor b and depth d, a BFS frontier can grow exponentially in d. Depth-first tree traversal can keep only the current branch and pending siblings, but may visit much deeper nodes. Do not apply tree bounds uncritically to graph implementations.
Practice
Write the queue contents after A and B are removed. Then remove A→G and predict BFS on the changed graph. Explain why a visited set keyed only by room would be wrong if the agent’s remaining battery changed which moves are permitted: battery must then be part of the state. Next, learn to prioritize accumulated cost and impose a depth bound.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Breadth-first and depth-first search — understanding check
Apply uninformed search to finite directed graphs and reason about algorithm guarantees.
Which pending route does BFS remove next?
What does BFS return from A to G in the example?
Why does the lesson DFS push neighbors in reverse listing order?
What does marking a state as seen when enqueuing it accomplish in the lesson BFS?
A correct BFS exhausts the reachable states of a finite, static graph without finding a goal. What can it conclude?