20. Graphs and Traversal#
A facilities team wants to know which rooms a visitor can reach from the lobby and how many doorways the shortest route uses. A dispatcher wants every delivery stop that a depot can serve, and a workflow designer wants to confirm that an approval step has all of its prerequisites. Each question is about items and the relationships between them, and each is answered by the same model: a graph of vertices and edges. This chapter defines that model and its contracts, stores it as an adjacency matrix or adjacency collections, and then discovers what the stored connections imply with breadth-first and depth-first search. It applies the queue of Chapter 15 and the recursive calls of Chapter 17 to a structure that, unlike a tree, may contain cycles and shared destinations.
Graph model: A set of vertices and a set of edges, each edge undirected or directed and optionally weighted. The vertex set is kept separate from the edge set so an isolated room, device, or customer is not lost.
Representation tradeoff: An adjacency matrix answers a pair lookup in constant time but costs Θ(V²) storage. Adjacency collections cost Θ(V + E) and enumerate a vertex’s neighbors in time proportional to its degree.
Breadth-first search: A queue of discovered vertices processes the graph in distance layers. Marking a vertex when it is enqueued, and recording its predecessor at that moment, yields minimum-hop routes in an unweighted graph.
Depth-first search: A recursive call finishes one branch before resuming its caller’s suspended neighbor loop. A discovered set stops cycles from causing endless recursion, but a first DFS route need not be the shortest.
Components and verification: Repeating a search from each undiscovered vertex of an undirected graph labels its connected components. Checkable contracts for distances, predecessors, and entry and exit events let a traversal result be verified rather than trusted.
Section 20.1 introduces vertices, edges, direction, degree, weights, walks, paths, cycles, and the simple-graph contract that the chapter’s examples adopt. Section 20.2 compares the adjacency matrix with list, set, and dictionary neighbor collections, measures density, and builds a protected RouteGraph whose SetEdge, RemoveEdge, RemoveVertex, and IsValid methods preserve the undirected invariant. Section 20.3 traces breadth-first search with a queue, a distance map, and a predecessor map, then reconstructs a route from the predecessor chain. Section 20.4 traces recursive depth-first search as entry and exit events, extends reachability into a component report, explains why direction changes what connectivity means, and closes with the traversal-verification contracts. Weighted shortest paths wait for Chapter 24.
Chapter Video
9. Breadth-First Search (52:52) by MIT OpenCourseWare.
Hosted on YouTube; property of its original creator, embedded here for educational reference only.
This lecture develops BFS and shortest paths in unweighted graphs. Use the content sections for the C# representations, DFS frames, and component contracts.
Learning Objectives
By the end of this chapter, you will be able to:
Model a workplace situation as a graph by naming its vertices, its edges, whether each edge is directed or undirected, and what each weight measures, and state what the model omits.
Compute degree, indegree, and outdegree for a given vertex, and use the degree-sum identities (2E for an undirected graph, E for each directed total) as a representation check.
Classify a vertex sequence as a walk, a path, or a cycle, decide whether a graph is connected, and identify its connected components, including isolated vertices.
Compare an adjacency matrix with list, hash set, and dictionary adjacency collections by storage, direct edge lookup, neighbor enumeration, and update cost, and compute a graph’s density to inform the choice.
Trace RouteGraph operations that add, replace, and remove edges and vertices, and state the representation invariant that IsValid checks, including equal reverse weights and a degree sum of twice EdgeCount.
Trace breadth-first search with a queue, a distance map, and a predecessor map, reconstruct a minimum-hop route from the predecessor chain, and explain why a vertex must be marked when it is enqueued rather than when it is dequeued.
Trace recursive depth-first search as entry and exit events with explicit frames, label the connected components of an undirected graph with repeated searches, explain why directed reachability does not compute strongly connected components, and verify a traversal result with the chapter’s contracts.
Chapter Flow
Assignments contains the preview, connected lab, and homework.
Suggested three-meeting pace (110 minutes): read the relevant explanations and predict the selected example before class.
Meeting |
Minutes |
Guided focus |
|---|---|---|
1 |
35 |
graph assumptions and adjacency representations. |
2 |
40 |
BFS paths and dependency ordering. |
3 |
35 |
DFS, components, and traversal checks. |
Class uses selected traces, runs, and checks. Use the remaining worked examples and detailed API tables for practice and reference. Supporting readings are selected separately; lab and homework follow the core lessons.
Glossary
# |
Term |
Explanation |
|---|---|---|
1 |
Graph |
A set of vertices and a set of edges connecting them; vertices model items and edges model relationships. |
2 |
Vertex |
An explicitly represented item such as a room, a task, or a delivery stop; it exists even when no edge touches it. |
3 |
Edge |
A connection between two vertices, undirected or directed, with an optional weight. |
4 |
Isolated vertex |
A vertex with degree zero; it is still part of the graph and forms a component by itself. |
5 |
Undirected edge |
A two-way relationship; one logical edge between Hall and Lab connects them in both directions. |
6 |
Directed edge |
An edge with a source and a destination, also called an arc; Hall to Lab does not imply Lab to Hall. |
7 |
Degree |
The number of edges at a vertex; in a simple undirected graph, the number of distinct neighbors. |
8 |
Indegree and outdegree |
For a directed graph, the counts of incoming and outgoing edges at a vertex; each total equals E. |
9 |
Degree sum |
In an undirected graph the degrees add to 2E, which serves as a representation check, not a proof of correctness. |
10 |
Weighted graph |
A graph whose edges carry values such as minutes, cost, or capacity, with stated units and a stated rule for combining them. |
11 |
Adjacent |
Two vertices are adjacent when an edge directly connects them; a vertex’s neighbors are its adjacent vertices. |
12 |
Connected graph |
An undirected graph with a route between every pair of vertices. |
13 |
Connected component |
A maximal group of vertices in an undirected graph that are all reachable from one another. |
14 |
Walk |
A vertex sequence in which each consecutive pair is joined by an edge in the required direction; vertices and edges may repeat. |
15 |
Path |
A walk with no repeated vertices; its number of edges is one less than its number of listed vertices. |
16 |
Cycle |
A closed walk with no repeated edges or vertices except its start and end; at least three edges in a simple undirected graph. |
17 |
Simple graph |
A graph with no self-loops and at most one edge between any pair of vertices. |
18 |
Self-loop |
An edge that joins a vertex to itself; rejected by this chapter’s route contract. |
19 |
Multigraph |
A graph that may store several distinct edges between the same two endpoints, such as separate transport services. |
20 |
Graph contract |
The stated rules a graph implementation enforces, such as explicit vertices, existing endpoints, nonnegative weights, and no self-loops. |
21 |
Adjacency matrix |
A V by V table with one cell per ordered pair of vertices; a row holds outgoing connections and a column holds incoming ones. |
22 |
Nullable weight |
A matrix cell that distinguishes a missing edge (null) from an existing edge with weight zero. |
23 |
Adjacency list |
A representation that stores each vertex’s actual neighbors in a list, a set, or a neighbor dictionary. |
24 |
Neighbor dictionary |
An adjacency collection mapping each neighbor to its weight, giving expected constant-time lookup with one entry per neighbor. |
25 |
Density |
Actual edges divided by the maximum possible, V(V - 1) / 2 undirected or V(V - 1) directed; reported as zero for fewer than two vertices. |
26 |
Sparse and dense graphs |
A sparse graph has few edges relative to the maximum and favors adjacency collections; a dense one may favor a matrix. |
27 |
Representation invariant |
The rules a stored graph must satisfy at all times: every neighbor names an existing vertex, no self-loops, nonnegative and equal reverse weights, and degree sum 2 times EdgeCount. |
28 |
Defensive copy |
Returning a copied array of vertices or neighbors so a caller cannot change the stored graph through the returned collection. |
29 |
Breadth-first search (BFS) |
A traversal that uses a queue to discover vertices in layers of increasing hop distance from the source. |
30 |
Discovery |
First reaching a vertex and marking it, which happens when it is enqueued, before it is processed. |
31 |
Distance layer |
All vertices at the same hop count from the source; BFS completes one layer before starting the next. |
32 |
Predecessor |
The vertex from which another vertex was first discovered; following predecessors backward reconstructs a route. |
33 |
Route witness |
A concrete vertex sequence that demonstrates a claimed distance, checked edge by edge rather than trusted. |
34 |
Reachability |
Whether a route exists from a starting vertex to a target; an unreachable known vertex has no predecessor chain. |
35 |
Neighbor order |
The order in which a vertex’s neighbors are examined; it can change which equally short route is chosen but not the minimum hop count. |
36 |
Depth-first search (DFS) |
A traversal that follows one neighbor to completion before resuming the caller’s remaining neighbors, usually written recursively. |
37 |
DFS frame |
An active call holding a vertex and its suspended position in that vertex’s neighbor loop. |
38 |
Enter and exit events |
The moment a vertex is first discovered by DFS and the moment its neighbor loop completes; each vertex has one of each. |
39 |
Discovered set |
The visited state shared by all searches in a traversal; it prevents a second discovery and endless recursion on cycles. |
40 |
Component report |
The labeling produced by starting a new search from each still-undiscovered vertex of an undirected graph. |
41 |
Strongly connected component |
A set of vertices in a directed graph that can all reach one another; not computed by repeated forward searches. |
42 |
Traversal cost |
O(V + E) time for a complete traversal over adjacency lists, with O(V) auxiliary space for visited state, predecessors, and the queue or stack. |
43 |
Traversal verification |
Checks that a BFS result has distance zero at the source and each predecessor one layer earlier, and that a DFS result has nested entry and exit intervals. |
44 |
Path certificate |
Evidence that establishes a route and, with appropriate layer/edge conditions, its minimum hop distance. |