All chapters[•]Data StructuresChapter 09
Data Structures · Chapter 9

Graphs and Graph AlgorithmsData Structures · Chapter 9

A subway map, a social network and the web are the same picture: dots and lines. This chapter stores such a graph, walks through it, finds the cheapest route between two points and the cheapest way to connect all of them. It is also where the structures of the whole course meet: a queue gives breadth-first search, a stack or recursion gives depth-first search, a heap gives Dijkstra's shortest paths, and union-find gives Kruskal's minimum spanning tree.

Instructors: Boxi Yu · Yintong Huo · Python and Java versions (switch at the top) · Every program here has been run, and every output shown is the real output. · All chapters

Walk through the example graph

Seven towns A–G joined by eleven weighted roads. Choose breadth-first search, depth-first search or Dijkstra and press Step: the vertex being explored, the frontier (a queue, a stack or a priority queue) and the discovered distances change together, and a counter shows how many adjacency entries have been read.

Why this matters

about 100–120 minutes (4 videos of 11–12 minutes plus the exercises).

Graphs are the general shape of "things and their connections"

Routes, friendships, links, dependencies between tasks, circuits: the same few questions come up every time. What is connected to what? What is the fewest steps, or the cheapest route? What is the cheapest way to connect everything?

Every earlier chapter is a part here

The adjacency list is a dictionary or map of lists (chapters 2 and 7), BFS uses a queue and DFS a stack or recursion (chapters 3 and 4), Dijkstra needs a priority queue (chapter 8) and Kruskal needs union-find, a small forest of trees (chapter 5). Choosing the right one for each job is what makes the algorithms fast.

The cost depends on how the graph is stored

For a sparse graph an adjacency list needs about V + E space and a search costs V + E steps; a matrix needs V² cells even when nearly all are empty. Most real graphs are sparse, so this decision decides whether a program is usable on a million vertices.

5 parts

Four videos with their notes, then the summary and practice. Read them in order.

01

Graph representations

A graph is vertices plus edges, directed or not, with or without weights. A program can store it as an edge list, an adjacency list or an adjacency matrix. They differ in space and in two costs: is there an edge u–v? and who are the neighbours of v? The adjacency list is the usual choice, because real graphs are mostly sparse.

vertexedgedirectedweightdegreepathcycleconnectededge listadjacency listadjacency matrixsparsedense
Open →
02

BFS and DFS

Both searches keep a frontier of vertices that are discovered but not yet explored; the only choice is which one to take next. Take the oldest (a queue) and you get breadth-first search, which explores in rings and reaches every vertex by a route with the fewest edges. Take the newest (a stack, or recursion) and you get depth-first search, which dives as deep as it can and then backs up; its discovery and finish times expose cycles. Both cost O(V + E).

frontierqueuestackBFSDFSlevelparentdiscovery timefinish timecycleO(V + E)
Open →
03

Dijkstra's shortest paths

To find the cheapest route, keep a tentative distance for every vertex and always settle the closest unsettled one (a priority queue keyed by distance). Settling a vertex relaxes its edges: does going through it make the route to a neighbour cheaper? With non-negative weights the closest unsettled vertex can never be beaten later, so its distance is final. A heap makes it O((V + E) log V); a negative edge breaks the argument.

weighted shortest pathtentative distancesettlerelaxpriority queuelazy deletionstale entryshortest-path treenegative edgeBellman–Ford
Open →
04

Minimum spanning trees and union-find

A minimum spanning tree (MST) connects all the vertices with V − 1 edges, no cycle, and the least total weight. A greedy rule is safe because of the cut property: the cheapest edge between any two groups of vertices belongs to the MST. Kruskal takes edges cheapest-first and skips any that would close a cycle; union-find answers "would it?" almost in constant time. Prim grows one tree from a start vertex, always adding the cheapest edge that leaves the tree.

spanning treeminimum spanning treecut propertyKruskalunion-findunion by sizepath compressionPrimO(E log V)
Open →
05

Summary and practice

A one-page map of the chapter, five self-check questions, ten exercises with solutions, and a way to test claims an AI makes about complexity.

self-checkexercises
Open →

How to use these notes

Watch · Predict · Step through · Practise

STEP 1

Watch

Each part starts with its video, 8–10 minutes, in Python or Java.

STEP 2

Predict

Answer the amber Predict box before you open the answer.

STEP 3

Step through

The interactive demos are being added; each one is described where it will appear.

STEP 4

Practise

Finish with the self-check and the exercises, with templates in your language.