Graphs, breadth-first search, and depth-first search
A graph connects vertices with edges. Unlike a tree, it can contain cycles, multiple routes between vertices, and disconnected components. A visited set prevents a cycle from sending the search around the same vertices indefinitely.
This lesson uses an invented undirected network with vertices A through E.
An adjacency dictionary maps each vertex to its neighbors. Every vertex appears
as a key, including isolated vertices, and every undirected edge appears in both
endpoint lists. Neighbor order determines traversal order, but not distance.
Find distances with a queue
Section titled “Find distances with a queue”Return the minimum number of edges from a start vertex to each reachable vertex. Each edge has unit cost. Breadth-first search, or BFS, removes vertices from a queue in the order they entered it.
The queue contains the current distance layer followed by the next layer. When BFS first discovers a neighbor, no shorter route to that neighbor remains unexamined. Mark the neighbor when you enqueue it, so two parents cannot add it twice.
from collections import deque
def breadth_first_distances( graph: dict[str, list[str]], start: str) -> dict[str, int]: """Return unweighted shortest distances from one vertex.
Args: graph: Adjacency lists with every neighbor also present as a key. start: Vertex from which to search.
Returns: Distances for reachable vertices, including zero for start.
Raises: ValueError: If start is not a graph vertex. """ if start not in graph: raise ValueError("start must be a graph vertex") distances = {start: 0} frontier = deque([start]) while frontier: vertex = frontier.popleft() for neighbor in graph[vertex]: if neighbor not in distances: distances[neighbor] = distances[vertex] + 1 frontier.append(neighbor) return distances
graph = { "A": ["B", "C"], "B": ["A", "D"], "C": ["A", "D"], "D": ["B", "C"], "E": [],}print("Distances from A:", breadth_first_distances(graph, "A"))print("Distances from E:", breadth_first_distances(graph, "E"))
distances = {"A": 0}frontier = deque(["A"])print("Initial queue:", list(frontier))while frontier: vertex = frontier.popleft() for neighbor in graph[vertex]: if neighbor not in distances: distances[neighbor] = distances[vertex] + 1 frontier.append(neighbor) print("Expanded", vertex, "queue", list(frontier), "discovered", list(distances))Distances from A: {'A': 0, 'B': 1, 'C': 1, 'D': 2}Distances from E: {'E': 0}Initial queue: ['A']Expanded A queue ['B', 'C'] discovered ['A', 'B', 'C']Expanded B queue ['C', 'D'] discovered ['A', 'B', 'C', 'D']Expanded C queue ['D'] discovered ['A', 'B', 'C', 'D']Expanded D queue [] discovered ['A', 'B', 'C', 'D']Vertex E is absent from the result from A because no route connects them.
Do not assign an unreachable vertex distance zero; zero already describes the
start vertex. Ordinary BFS does not solve the general weighted shortest-path
problem because edge count and total weight can disagree.
Explore components with a stack
Section titled “Explore components with a stack”Depth-first search, or DFS, uses the most recently added vertex next. An explicit stack avoids a recursive call for each depth level. The algorithm below starts a new search whenever the outer loop encounters an unseen vertex.
For an undirected graph, each such search visits exactly one connected component. The same procedure on a directed graph does not compute strongly connected components. Direction changes which vertices can reach each other.
def connected_components(graph: dict[str, list[str]]) -> list[list[str]]: """Return DFS components of an undirected graph.
Args: graph: Complete symmetric adjacency lists for an undirected graph.
Returns: Components in dictionary order, with DFS expansion within each one. """ visited: set[str] = set() components: list[list[str]] = [] for start in graph: if start in visited: continue visited.add(start) stack = [start] component: list[str] = [] while stack: vertex = stack.pop() component.append(vertex) for neighbor in graph[vertex]: if neighbor not in visited: visited.add(neighbor) stack.append(neighbor) components.append(component) return components
print("DFS components:", connected_components(graph))assert connected_components({}) == []assert connected_components({"A": []}) == [["A"]]assert breadth_first_distances({"A": ["A"]}, "A") == {"A": 0}assert breadth_first_distances(graph, "A")["D"] == 2print("The empty, isolated, self-loop, and cycle cases pass.")DFS components: [['A', 'C', 'D', 'B'], ['E']]The empty, isolated, self-loop, and cycle cases pass.Marking at insertion keeps each vertex in the frontier at most once. The visited set grows and never loses a vertex. When a component’s stack empties, every neighbor of every visited vertex is already visited, so no reachable vertex remains outside that component.
Derive the costs
Section titled “Derive the costs”Let V be the vertex count and E the undirected edge count. A complete search
visits each vertex once and inspects each adjacency entry once. Each undirected
edge contributes two entries, so total expected time is O(V + E), with expected
constant-time dictionary and set operations.
BFS from one start has that bound over the reachable subgraph. The component
algorithm covers all vertices, including isolated vertices. Its auxiliary space
is O(V) for the visited set and frontier. The returned component lists also
occupy O(V) space. BFS uses at most O(V) frontier space and returns at most
O(V) distances. The input adjacency representation occupies O(V + E) space.
These bounds describe breadth_first_distances and connected_components.
The demonstration also copies the queue and the discovered vertices after each expansion.
Those display operations add work beyond the traversal itself.
Hash collisions can worsen these expected bounds. Vertex comparisons and hashes
also have a cost; this lesson treats the short vertex labels as constant-size
keys. Replacing deque.popleft() with list.pop(0) adds reference shifts and can
make a wide traversal quadratic.
Derive neighbors from a grid
Section titled “Derive neighbors from a grid”A grid does not need a stored adjacency list. A cell’s row and column define its possible neighbors. The next example permits movement up, down, left, or right; diagonal movement is not an edge.
Each S is a source, . is an open cell, and # is a wall. Return the
distance to the nearest source for every cell. Use -1 for an unreachable
open cell and -2 for a wall. These values cannot be confused with a source’s
distance of zero. All moves have unit cost.
def nearest_source_distances(grid: list[str]) -> list[list[int]]: """Find grid distances from several sources through unit-cost moves.
Args: grid: Equal-length, nonempty rows containing S, ., or #. An empty list represents an empty grid. The input remains unchanged.
Returns: Nearest-source distances, with -1 for unreachable cells and -2 for walls. An empty grid produces an empty list.
Raises: ValueError: If rows are empty, unequal, or contain another character. """ if not grid: return [] width = len(grid[0]) if width == 0 or any(len(row) != width for row in grid): raise ValueError("grid rows must be nonempty and equal in length") if any(character not in "S.#" for row in grid for character in row): raise ValueError("grid cells must be S, ., or #") distances = [[-1] * width for _ in grid] frontier = deque() for row, cells in enumerate(grid): for column, character in enumerate(cells): if character == "#": distances[row][column] = -2 elif character == "S": distances[row][column] = 0 frontier.append((row, column)) while frontier: row, column = frontier.popleft() for row_step, column_step in ((-1, 0), (1, 0), (0, -1), (0, 1)): next_row = row + row_step next_column = column + column_step if not (0 <= next_row < len(grid) and 0 <= next_column < width): continue if distances[next_row][next_column] != -1: continue distances[next_row][next_column] = distances[row][column] + 1 frontier.append((next_row, next_column)) return distances
room_grid = ["S..#.", ".#...", "...#S"]print("Distance to the nearest source:")for distance_row in nearest_source_distances(room_grid): print(distance_row)print("Walls and unreachable cells:")for distance_row in nearest_source_distances(["S#.", "###", "..S"]): print(distance_row)Distance to the nearest source:[0, 1, 2, -2, 2][1, -2, 3, 2, 1][2, 3, 4, -2, 0]Walls and unreachable cells:[0, -2, -1][-2, -2, -2][2, 1, 0]Every source enters the queue before expansion starts. The queue therefore processes distance layers across all sources together. The first discovery of a cell gives its shortest distance from any source, and its stored distance prevents later insertion.
Starting a separate complete BFS from every source repeats work. Starting from
only the first source solves a different problem. For r rows and c columns,
initialization and traversal take O(rc) time because each cell has at most
four neighbors. The queue uses O(rc) auxiliary space in the worst case, and
the returned matrix uses another O(rc) space.
The input remains unchanged. A grid with no sources leaves every open cell unreachable. If moving across an edge has a varying cost, this distance-layer argument no longer applies.
assert nearest_source_distances([]) == []assert nearest_source_distances(["S"]) == [[0]]assert nearest_source_distances(["."]) == [[-1]]assert nearest_source_distances(["#"]) == [[-2]]assert nearest_source_distances(["S.S"]) == [[0, 1, 0]]assert nearest_source_distances(["S#."]) == [[0, -2, -1]]assert room_grid == ["S..#.", ".#...", "...#S"]print("Empty, isolated, blocked, and multiple-source grid checks pass.")Empty, isolated, blocked, and multiple-source grid checks pass.Practice
Section titled “Practice”Flood Fill represents neighbors implicitly through grid coordinates. Define the valid neighbor rule before you choose a queue or a stack.
Number of Islands applies component discovery to a grid. Explain whether you store a visited set or mutate the input cells, because that choice changes the auxiliary space account.
Download the Python source to run the complete example locally.
Further reading
Section titled “Further reading”MIT’s graph lecture notes include separate BFS and DFS lectures. They connect traversal invariants to shortest paths and graph structure.
Python’s deque documentation describes efficient operations at both ends. It explains the queue operations used by the BFS implementation.