The general definition, narrowed to this week's actual data.
CampusNav's campus map will be undirected (walkways go both ways)
and weighted (walking minutes) - but the same definition covers
one-way, unweighted graphs too (e.g., "who follows whom" online).
Key Words Today
Degree: how many edges touch a vertex - e.g., the Library's degree is how many walkways lead to it.
Adjacent: two vertices connected directly by an edge.
Path: a sequence of edges connecting one vertex to another.
Cycle: a path that starts and ends at the same vertex - relevant later in this deck, and central to Week 14's negative-cycle discussion.
Sparse / dense: whether a graph has close to the fewest possible edges (sparse) or close to the most possible (dense) - today's whole argument hinges on this.
Two Design Choices Every Graph Makes
Even mapping five friends by hand raises this exact question: how would you describe that picture to a computer, using only numbers or short lists? Every graph answers two design questions first.
Directed vs. undirected
Instagram "follows": directed - you can follow someone who doesn't follow you back.
Campus walkways: undirected - if you can walk Gate → Library, you can walk back.
Weighted vs. unweighted
"Is there a road between these two cities?": unweighted - yes/no.
"How many minutes does that road take?": weighted - a number on every edge.
Every graph you'll ever build makes both choices before you write a
single line of representation code.
CampusNav's Campus, as a Graph
Six real locations. Undirected. Weighted by walking minutes.
3245263GLCDYF
G = Gate, L = Library, C = CS-Building, D = Dorm, Y = Gym, F = Cafeteria. Edge labels = walking minutes.
Graph representations · worked example 1 of 3 (simple)
Three Nodes: A-B-C
The smallest graph that still has a non-edge worth representing.
GoalBuild both representations for the smallest graph that isn't just one edge.
1
Setup
3 vertices A, B, C. Edges: A-B, B-C (undirected, unweighted). Notice: A and C are not directly connected.
2
Adjacency matrix
A 3×3 grid. Row A: [-, 1, -]. Row B: [1, -, 1]. Row C: [-, 1, -]. 9 cells total, only 4 marked (2 edges, each stored twice for symmetry).
3
Adjacency list
A → [B]. B → [A, C]. C → [B]. 3 headers + 4 neighbor entries (2 edges × 2) = 7 entries total.
✓
ConclusionSame graph: 9 matrix cells vs. 7 list entries - the list is already smaller, even at this toy scale.
💡
Key takeawayA non-edge (A-C) costs the matrix a cell it must still store as "-"; the list simply never mentions it.
Graph representations · worked example 2 of 3 (moderate)
The Actual Campus, Six Nodes
Same two representations, now on CampusNav's real six-location graph.
GoalBuild both representations for Gate, Library, CS-Building, Dorm, Gym, Cafeteria.
6×6 = 36 cells total. Only 14 are filled (7 edges × 2, for symmetry) - the other 22 are "-".
4
Count both
List: V + 2E = 6 + 2(7) = 20 entries. Matrix: V² = 36 cells. The list is already smaller here, before the campus even grows.
✓
ConclusionSame graph, verified: 20 list entries vs. 36 matrix cells - a gap that only widens as the campus grows.
💡
Key takeawayThe matrix's size depends only on V; the list's size depends on what's actually connected - that's the whole reason it wins on sparse graphs.
Graph representations · worked example 3 of 3 (harder)
Adding a Seventh Location
CampusNav adds Parking Lot (P), connected only to the Gate, weight 2.
GoalShow which representation's cost grows faster from one new vertex and one new edge.
1
Updated graph
Now V=7, E=8. G's list becomes G→L(3),D(4),P(2).
2
Matrix cost
V² = 7² = 49 cells, up from 36 - a jump of 13 cells for one new vertex and one new edge.
3
List cost
V + 2E = 7 + 16 = 23 entries, up from 20 - a jump of just 3 entries: one header for P, plus P's one neighbor entry and G's one new neighbor entry.
★
Why this matters
The matrix's cost grew over 4× faster than the list's, for the exact same change - not a one-time fluke, a structural property of O(V²) space.
✓
ConclusionOne new sparse vertex costs the matrix 13 cells and the list 3 entries - the growth-rate gap is the whole argument, not just the absolute numbers.
💡
Key takeawayO(V²) is the worse growth rate, not just a bigger constant - this is the concrete instance that proves it.
Complexity Trade-off
Operation
Adjacency Matrix
Adjacency List
Space
O(V²)
O(V + E)
Is (u, v) an edge?
O(1)
O(deg(u))
List all neighbors of u
O(V)
O(deg(u))
Iterate all edges
O(V²)
O(V + E)
Add a new vertex
O(V²) (resize/copy)
O(1)
On CampusNav's 6-node demo graph the difference looks small. It stops
looking small the moment the graph gets big - next slide.
Why It Matters: the Full DEU Campus
Same two representations, now at real scale.
The real Dong-Eui University (DEU) campus isn't 6 locations - it's every building,
junction, and walkway: roughly 300 nodes, each realistically connected to
only about 4 neighboring paths (a sparse network, like real sidewalks - not
a place where everywhere connects to everywhere). Note this counts locations
(buildings and path junctions), a coarser unit than the ~1,200 individual rooms the directory-lookup weeks used - one building is one node here, but
dozens of rooms there.
6-node demo (V=6, E=7)
Full DEU campus (V≈300, E≈600)
Adjacency matrix cells
36
90,000
Adjacency list entries
6 + 2×7 = 20
300 + 2×600 = 1,500
The Storage Gap, at Full Scale
36 cells was a toy. 90,000 is where the choice starts to matter.
At full scale the matrix needs 60× more storage than the list -
and 88,500 of its 90,000 cells would just be empty. This is exactly
why CampusNav will use an adjacency list once it goes campus-wide.
Key Words Today
Traversal: systematically visiting every reachable vertex in a graph.
Queue: a first-in-first-out list - what BFS uses to decide what to visit next.
Stack (or recursion): a last-in-first-out structure - what DFS uses instead.
Connectivity: whether every vertex can be reached from a given start vertex.
Two Data Structures: Queue and Stack
Not new algorithms - two ways of ordering "what to do next," each with exactly two operations. (CLRS 4th ed, §10.1)
Queue - FIFO (first in, first out).enqueue (add to the back), dequeue (remove from the front).
Operation
Queue (front → back)
enqueue A
[A]
enqueue B
[A, B]
dequeue → A
[B]
BFS uses a queue: the first vertex found is the first one explored further.
Stack - LIFO (last in, first out).push (add to the top), pop
(remove from the top).
Operation
Stack (bottom → top)
push A
[A]
push B
[A, B]
pop → B
[A]
DFS uses a stack - the same LIFO structure as Week 4's call stack.
A Third Abstract Data Type (ADT): Priority Queue
Not used until Week 14 - introduced now so the name isn't new when Dijkstra needs it. (CLRS 4th ed, §6.5)
A priority queue holds elements each tagged with a priority (for
Dijkstra, a distance). Two operations: insert (add an element with
its priority), extract-min (remove and return the element with the
smallest priority).
Given fact, not proven here: a binary heap implements a
priority queue with $O(\log n)$ insert and $O(\log n)$
extract-min. Treat this as a tool this course hands you for
Week 14's Dijkstra, not something to build or prove from scratch.
Storing the Network Isn't Enough
We can now hold the whole map in memory. Can we use it yet?
Both representations answer "what connects to what." Neither one, by
itself, answers a question CampusNav needs constantly: "starting from
the Gate, what can I reach, and in what order should I visit it?"
That requires actually walking the graph, one vertex at a time - a traversal. There are exactly two fundamental ways to do it.
Breadth-First Search (BFS)
BFS(G, s):
mark s visited; enqueue s onto Q
while Q is not empty:
u = dequeue(Q)
visit(u)
for each neighbor v of u:
if v not visited:
mark v visited; enqueue v
Visits vertices in layers - everyone 1 step away, then everyone 2 steps away, and so on.
Uses a queue: the first vertex found is the first one explored further.
On an unweighted graph, BFS's discovery order already gives the shortest path (fewest edges) from the start - full weighted shortest paths are next week.
Runtime: O(V + E) - every vertex enqueued once, every edge examined once.
(CLRS 4th ed, §20.2)
BFS · worked example 1 of 3 (simple)
Three Nodes: A-B-C
A straight-line graph - the smallest case that still uses the queue for real.
GoalTrace BFS from A on A-B-C and watch the queue fill and drain.
1
Start
A→[B], B→[A,C], C→[B]. Mark A visited, enqueue A. Q = [A].
→
2
Dequeue A
Visit A. Neighbor B unvisited: mark visited, enqueue. Q = [B].
→
3
Dequeue B, then C
Visit B; neighbor C unvisited, enqueue → Q=[C]. Dequeue C; neighbor B already visited. Q=[].
✓
ConclusionVisit order: A, B, C - identical to what DFS will find on this same tiny graph.
💡
Key takeawayThe queue's FIFO order is what forces "nearest first" - even this tiny trace already shows it.
BFS · worked example 2 of 3 (moderate)
The Campus Graph, Queue by Queue
Same six-location graph as this week's core example. G→[L,D] L→[G,C,Y] C→[L,F] D→[G,Y] Y→[L,D,F] F→[Y,C].
GoalTrace the queue's contents from Gate, round by round.
Dequeue D - both neighbors already visited, nothing new → Q=[C,Y]. Dequeue C, enqueue F → Q=[Y,F].
→
3
Dequeue Y, then F
Dequeue Y - all neighbors already visited → Q=[F]. Dequeue F - all neighbors already visited → Q=[].
→
4
Reading the order
Visit order, read down each dequeue: G, L, D, C, Y, F - exactly what FIFO order guarantees: whichever vertex enters the queue first is explored first.
✓
ConclusionG, L, D, C, Y, F - six dequeues, matching the graph's layer structure exactly (Gate's layer, then its neighbors' layer, then theirs).
💡
Key takeawayThe queue never needs to "decide" an order - FIFO alone reconstructs the layer-by-layer structure.
BFS · worked example 3 of 3 (harder)
A Seventh Node: Does Visit Order Mean Distance?
CampusNav adds Parking Lot (P), connected only to the Gate: G→[L,D,P].
GoalShow that visit order and hop-count are related, but not the same number.
1
Round 1
Enqueue G. Dequeue G, enqueue L,D,P (in list order) → Q=[L,D,P].
→
2
Rounds 2-4
Dequeue L, enqueue C,Y → Q=[D,P,C,Y]. Dequeue D - nothing new → Q=[P,C,Y]. Dequeue P - its only neighbor (G) already visited → Q=[C,Y].
→
3
Rounds 5-7
Dequeue C, enqueue F → Q=[Y,F]. Dequeue Y, then F - nothing left to enqueue. Visit order: G, L, D, P, C, Y, F.
★
The catch
Parking Lot is visited 4th overall - but it's only 1 hop from Gate, exactly like Library and Dorm. It's visited later only because it's third in G's neighbor list, not because it's farther away.
✓
ConclusionVisit order depends on neighbor-list order; hop-count (layer) depends only on the graph's actual structure - BFS guarantees the layers, not the exact position within a layer.
💡
Key takeaway"Visited 4th" and "4 hops away" are different claims - only BFS's layer grouping, not its raw visit sequence, is the guarantee.
Depth-First Search (DFS)
DFS(G, u):
mark u visited; visit(u)
for each neighbor v of u:
if v not visited:
DFS(G, v)
Plunges as deep as possible down one path before backtracking - the opposite instinct from BFS.
Uses a stack, usually the implicit call stack via recursion (as above), or an explicit stack iteratively.
A natural fit for "is the whole graph connected?" or "does this graph have a cycle?" - not for shortest paths.
Runtime: O(V + E) - same bound as BFS, same reason.
(CLRS 4th ed, §20.3)
DFS · worked example 1 of 3 (simple)
Three Nodes: A-B-C
Same tiny graph as BFS's simple example - now with the opposite strategy.
GoalTrace DFS from A on A-B-C and compare its order to BFS's.
1
DFS(A)
Mark A visited. Neighbor B unvisited → recurse into DFS(B).
→
2
DFS(B)
Mark B visited. Neighbor A visited, neighbor C unvisited → recurse into DFS(C).
→
3
DFS(C)
Mark C visited. Neighbor B already visited - nothing left, DFS(C) finishes, then DFS(B), then DFS(A) unwind in reverse.
✓
ConclusionDiscovery order: A, B, C - identical to BFS's order here, because a straight line offers no branch for the two strategies to disagree on.
💡
Key takeawayBFS and DFS only visibly differ once a graph actually branches - which is exactly what the next example does.
DFS · worked example 2 of 3 (moderate)
The Campus Graph, One Call Chain
Same adjacency list as BFS's moderate example - DFS always recurses into the first unvisited neighbor listed.
GoalTrace the full discovery-then-finish cycle from Gate.
1
Plunge: G, L, C
DFS(G): d=1, recurse to L (first unvisited neighbor). DFS(L): d=2, recurse to C. DFS(C): d=3, recurse to F.
→
2
Plunge: F, Y, D
DFS(F): d=4, recurse to Y. DFS(Y): d=5, recurse to D. DFS(D): d=6 - neighbors G, Y both already on the stack.
→
3
Unwind
D has nothing left: finishes (f=7). Every enclosing call finishes right behind it, in exact reverse: Y(8), F(9), C(10), L(11), G(12).
→
4
Read the result
Discovery order: G, L, C, F, Y, D. Finish order is its exact mirror here, because this adjacency-list order never hands DFS a second unvisited branch to try.
✓
ConclusionOne call chain, six discoveries, six finishes, in exactly reverse order - the recursion stack made both orders automatic.
💡
Key takeawayAt the deepest point, the call stack literally holds all six waiting frames - not a metaphor, the exact structure a debugger would show you.
DFS · worked example 3 of 3 (harder)
Same Graph, Different Start: From the Library
Same adjacency list, same algorithm - only the starting vertex changes.
GoalShow that DFS's order, unlike BFS's layers, depends heavily on where it starts.
1
DFS(L) plunges
L's neighbors in order: G, C, Y. DFS(L) → DFS(G) (G's only unvisited neighbor is D) → DFS(D).
→
2
Continue plunging
DFS(D): neighbor G visited, neighbor Y unvisited → DFS(Y). DFS(Y): L, D visited, F unvisited → DFS(F).
→
3
Finish
DFS(F): neighbor Y visited, neighbor C unvisited → DFS(C). DFS(C): both neighbors (L, F) already visited - finishes, then every enclosing call unwinds.
★
Compare to Gate's start
Discovery order: L, G, D, Y, F, C - completely different from starting at Gate (G, L, C, F, Y, D), on the exact same graph.
✓
ConclusionSame six vertices, same edges, two different starting points, two unrelated discovery orders.
💡
Key takeawayDFS's order depends heavily on where it starts, unlike BFS's guarantee about hop-count layers - that guarantee is specific to BFS, not traversal in general.
DFS's Stack vs. Week 4's Call Stack
Not a metaphor - the same mechanism, revisited.
At the deepest point of the moderate-tier trace above, the call stack literally
holds six waiting frames: DFS(G) is paused waiting on DFS(L), which is paused
waiting on DFS(C), and so on down to DFS(D) - the exact same last-in-first-out
structure as any recursive function traced back in Week 4's recursion
& recurrence unit. Recursive DFS is a stack-based algorithm; it
just uses the runtime's implicit call stack instead of a `push`/`pop`
structure you manage yourself. Implementing DFS iteratively with an
explicit stack produces the exact same discovery order - proof that
"recursion" and "stack" were never two different ideas here, just two
ways of writing one.
CampusNav: Tracing BFS and DFS from the Gate
Everything above, side by side, on the actual campus map.
Using the adjacency list (neighbors in the order each edge was added):
G→[L,D] L→[G,C,Y] C→[L,F] D→[G,Y] Y→[L,D,F] F→[Y,C]
B
BFS from Gate: G, then L & D, then C & Y, then F → G, L, D, C, Y, F
D
DFS from Gate: plunges G → L → C → F → Y → D → G, L, C, F, Y, D
Same start, same graph, same six stops - a completely different
order, because one explores layer by layer and the other commits to a
path first.
Common Mistakes
"Adjacency matrix is always fine - it's simpler." Fine at 6 nodes (36 cells). At the full campus (~300 nodes) it's 90,000 mostly-empty cells versus about 1,500 for a list - a 60× waste that gets worse, not better, as CampusNav grows. Matrix vs. list is a density decision, not a taste decision.
Forgetting an undirected edge is two list entries, not one. If G–L is a walkway, L must list G as a neighbor and G must list L - miss one direction and a traversal from the other side silently can't reach back.
Common Mistakes, Continued
Assuming DFS also finds the shortest path. Only BFS's layer-by-layer order guarantees fewest edges to reach each vertex on an unweighted graph; DFS's order says nothing about distance at all - DFS can easily reach a vertex by a long, winding path first.
Where This Shows Up Everywhere Else
This isn't only about CampusNav.
Social networks (who's reachable within 2 connections), web crawlers
(BFS from a seed page), dependency resolution (DFS to detect a cycle
in a build system), maze and puzzle solvers, network broadcast and
routing - all the same two traversal ideas, over and over.
Why This Comes Up in Interviews
The same two decisions, asked about a hundred different problems.
"Given a graph, traverse it" is one of the most frequently asked
technical-interview question shapes, precisely because both the
representation choice (matrix vs. list) and the traversal choice (BFS
vs. DFS) have real, defensible right answers depending on the problem.
What Graph Representation Cannot Do
We can now store CampusNav's entire campus as a real network, and
BFS/DFS let us visit - and confirm we can reach - every location from
a given start. But neither traversal, as covered this week, answers
the single most common request the "Get Directions" feature actually
gets: not "can I reach the Cafeteria," but "what's the cheapest
(fastest-walking) way to reach it." Reachability is not the same
question as shortest weighted path.
Next Week
Week 13 leaves finding the cheapest path between two locations, not
just any reachable path unsolved. Week 14, Shortest Path,
addresses it: Dijkstra's algorithm (and, when a walkway "credit" makes
an edge weight negative, Bellman-Ford) computes CampusNav's actual
"Get Directions" feature over this exact campus graph.
Where This Week Lives in CLRS
Everything above, mapped to the textbook - and where to look if you want more.
This week's topic
CLRS 4th ed
Graph representations (adjacency list / matrix)
§20.1
Breadth-first search
§20.2
Depth-first search
§20.3
Queue / stack ADTs
§10.1
Priority queue (stated as a tool, not proven)
§6.5
If you want to go deeper (not required this semester):
CLRS §20.4 (topological sort - ordering tasks with dependencies)
and §20.5 (strongly connected components - which vertices can
all reach each other) are the natural next structures built on top of
this week's representations and traversals.
Summary
A graph is vertices + edges, directed/undirected, weighted/unweighted - the formal shape behind "what connects to what."
Adjacency matrix (O(V²) space, O(1) edge lookup) and adjacency list (O(V+E) space, O(deg(u)) edge lookup) store the same graph differently - and the real DEU campus's sparsity (≈300 nodes, ≈600 edges) makes the list the clear winner, 60× less storage.
BFS (queue, layer-by-layer, shortest paths on unweighted graphs) and DFS (stack/recursion, deep-first, connectivity) both traverse a graph in O(V+E), but visit it in different orders.
Assignment 4 released this week (Dynamic Programming & Graphs) - see materials/assignments/assignment4.md. Due Week 15, before the final exam.
New: Week 13 Check - a short graded exercise on today's representations, BFS, and DFS, released now, due before Week 14 begins, separate from Assignment 4 (see materials/assignments/week13-check.html).
Summary, Continued
Reading: CLRS, Chapter 20 - §20.1 (representations), §20.2 (BFS), §20.3 (DFS); also §10.1 (queue/stack ADTs) and §6.5 (priority queues).
Prepare: think about how you'd find the shortest walking route on the campus graph if some walkways were much longer than others. Bring your intuition to Week 14.
Thank You
SLOT 1: Title
notes: Welcome the class. Say: "Every feature we've built so far - the room directory, the tour planner, study-buddy matching - treats CampusNav's data as a flat list. Today that stops being enough." Mention Assignment 4 is now posted, due Week 15, and briefly point at materials/assignments/assignment4.md. Also flag the new Week 13 Check, due before Week 14 begins.
SLOT 2: Where we are
notes: Point at the row. Say: "We've spent three weeks on paradigms for arrays and sequences. Today CampusNav's data stops being a line and becomes a network."
SLOT 3: Recap + open wound
SLOT 4: The pain (Act 1 / MOTIVATE), zero jargon
notes: Do not say "graph," "vertex," or "edge" here. Let the class feel the mess first.
SLOT 5: Cost of not knowing
SLOT 6: Driving question
SLOT 7: Learning outcomes
NEW: Key Words Today, session 1 (moved after Act 1 / MOTIVATE per SPINE.md's no-definition-before-slot-8 rule)
notes: Read each term aloud once. Say these get a precise definition later this session.
SLOT 8: Origin
SLOT 9: Core concept
NEW: Key Words Today, session 2
notes: Read each term aloud. Say "sparse vs. dense" returns in about ten minutes with real numbers.
Act 3 / BUILD: idea slide, folds in the old warm-up's payload as a teacher-delivered lead-in
NEW: dense worked example, graph representations, simple tier
NEW: dense worked example, graph representations, moderate tier
NEW: dense worked example, graph representations, harder tier
NEW: Key Words Today, session 3
notes: Read each term aloud. Say these four words get a proper definition, not just a name-drop, on the next two slides.
Merged: two data-structure slides into one two-col idea slide
NEW: priority queue, a third ADT, stated as a tool not proven here
NEW: dense worked example, BFS, simple tier
NEW: dense worked example, BFS, moderate tier (absorbs "Reading the Queue Trace")
NEW: dense worked example, BFS, harder tier (absorbs the extended-graph follow-up questions)
NEW: dense worked example, DFS, simple tier
NEW: dense worked example, DFS, moderate tier
NEW: dense worked example, DFS, harder tier (absorbs the different-start follow-up question)