Simple Algorithm
Algorithms & Data Structures · Brute Force · 18 min

Graph Algorithms

Networks of things, and the algorithms that explore, route and connect them.

In 2011, researchers found that two of Facebook's 721 million active users were separated, on average, by a chain of just 4.74 friendships. Distances like that, the fastest route across a city, a valid order for a software build and the cheapest way to wire up a neighborhood all come from a handful of algorithms that work on one simple object: dots joined by lines.

What you’ll learn

  • Model maps, social networks, dependencies and puzzles as graphs, and store a graph as adjacency lists or an adjacency matrix.
  • Explain how breadth-first and depth-first search explore a graph, and why breadth-first search finds the routes with the fewest edges.
  • Order tasks that have prerequisites, find cheapest routes with Dijkstra's algorithm, and connect every point at the least total cost with Kruskal's algorithm.
  • Recognize from the words of a problem which graph algorithm it calls for.

Dots and lines

A graph is a set of vertices (also called nodes) joined by edges. That is the whole definition, and it fits a surprising amount of the world:

SituationVerticesEdgesKind of graph
Road mapintersectionsroad segmentsdirected (one-way streets), weighted by travel time
Social networkpeoplefriendshipsundirected, unweighted
Course catalogcourses"must be taken before"directed, with no loops of prerequisites
Sliding-tile puzzlepositions of the tilessingle movesundirected and huge: the 3 × 3 puzzle alone has 181,440 reachable positions
We write nn for the number of vertices and mm for the number of edges.

A program usually stores a graph in one of two ways. An adjacency list keeps, for every vertex, the list of its neighbors. An adjacency matrix is an n×nn \times n table with a mark in row uu, column vv whenever uu and vv are joined.

The matrix answers "are uu and vv joined?" in one step, but it has n2n^2 cells even when every vertex has only a few neighbors. The lists need space proportional to n+mn + m, which is why most programs use them.

Predict before you look

The graph you will explore in the next step has 8 vertices and 10 undirected edges. How many entries do its adjacency lists hold in total?

Show the answer

20 entries

Each undirected edge between uu and vv appears twice: vv in uu's list and uu in vv's list, so there are 2×10=202 \times 10 = 20 entries. The matrix would have 8×8=648 \times 8 = 64 cells. For a road network with ten million intersections the gap is enormous: a few tens of millions of list entries against 101410^{14} matrix cells.

Exploring: breadth first and depth first

To explore a graph, start at one vertex and keep visiting vertices you can reach. The two classic strategies differ only in which discovered vertex they explore next.

  • Breadth-first search (BFS) explores in layers, like ripples on a pond: first the start, then every vertex one edge away, then every vertex two edges away, and so on. It keeps the discovered vertices in a queue: first in, first out.
  • Depth-first search (DFS) follows one path as deep as it can and backs up only when it reaches a vertex with no unvisited neighbors. It keeps its current path on a stack (last in, first out) or lets recursion keep it.
Check your understanding

Why does BFS reach every vertex along a path with the fewest possible edges?

  1. It explores the neighbors of each vertex in alphabetical order
  2. It finishes every vertex at distance kk before it touches any vertex at distance k+1k + 1
  3. It keeps the discovered vertices on a stack
  4. It tries every possible path and keeps the shortest one
Show the answer

B. It finishes every vertex at distance kk before it touches any vertex at distance k+1k + 1

The queue serves vertices in the order they were discovered, so all of layer kk leaves the queue before layer k+1k + 1 does. The first time BFS reaches a vertex is therefore along a path with as few edges as possible. The Optimized lesson turns this into a proof.

Think first If BFS finds the routes with the fewest edges, why would anyone use DFS?

DFS remembers only the path it is on, so it needs little memory on wide graphs, and the order in which it enters and leaves vertices exposes a graph's structure: cycles, dependencies, and the weak points of a network. Several lessons in this topic are built on that order.

Grids and mazes are graphs too

A maze on squared paper is a graph: every open square is a vertex, joined to the open squares above, below, left and right of it. Nobody writes this graph down. The search computes a square's neighbors only when it needs them, so the graph is implicit.

Puzzles work the same way: a position is a vertex, a move is an edge, and BFS from the starting position finds a solution with the fewest moves.

The paint-bucket tool of an image editor is the same kind of search: it starts at the clicked pixel and spreads to neighboring pixels of the same color, a flood fill. Start one flood fill from every land square of a map that no earlier fill has reached, and the number of fills is the number of islands: each fill covers one connected component.

Dependencies: an order that respects every arrow

Directed edges often mean "must happen before": a course before the course that requires it, a source file before the code that imports it. A topological order lists all the vertices so that every edge points forward. It exists exactly when the graph has no directed cycle, and such graphs have their own name: DAGs, directed acyclic graphs.

Kahn's algorithm does what a student planning a degree would do: take any course whose prerequisites are all done, cross it off, and repeat.

Think first What happens if the prerequisites contain a loop: A before B, B before C, and C before A?

None of the three ever has all its prerequisites done, so none is ever output: the algorithm stops with them left over. No valid order exists, and the leftovers point to the loop. This is how build tools and package managers detect circular dependencies.

The cheapest route: Dijkstra’s algorithm

Give every road a travel time and the question changes: not the fewest roads but the smallest total time, a shortest path in the weighted sense. Dijkstra's algorithm (1959) answers it with a greedy idea.

Keep a tentative distance for every vertex: 0 for the source, ∞\infty for the others. Repeatedly settle the unsettled vertex with the smallest tentative distance, then use each of its roads to lower its neighbors' tentative distances. A priority queue hands out the smallest one quickly.

That argument needs non-negative weights. With negative ones, such as a refund or the energy a car recovers going downhill, a vertex can be settled too early. The Bellman–Ford algorithm handles negative weights, at a higher cost.

Connecting everything cheaply

A town wants to lay fiber so that every building is connected, directly or through other buildings, at the lowest total cost. The answer is a minimum spanning tree: n−1n - 1 edges that connect all nn vertices with the smallest total weight. It never contains a cycle, because a cycle always has an edge you could remove and stay connected.

Kruskal's algorithm is greedy: sort the edges from cheapest to most expensive, and take each one unless it would close a cycle.

To tell quickly whether two vertices are already connected, Kruskal's algorithm keeps the groups of connected vertices in a union-find structure, which merges two groups and answers "same group?" in nearly constant time. Union-find is the tool whenever a problem asks "are these two connected?" while new connections keep arriving.

Which algorithm? Reading the problem

Most graph problems never say "graph". They talk about cities, friends, tasks or grid cells, and their words point to the technique:

The problem says…Technique
fewest moves, steps or hops, and every move costs the sameBFS
visit everything reachable; count the regions or islands; is there a loop?BFS or DFS, one flood fill per region
prerequisites, "must come before", is a schedule possible?Topological sort
cheapest or fastest route, and costs are never negativeDijkstra (with negative costs, Bellman–Ford)
connect everything at the lowest total costMinimum spanning tree (Kruskal or Prim)
"are these two connected?" while new links keep arrivingUnion-find
maximum throughput; the most pairs or assignmentsMaximum flow or matching
Check your understanding

A company must link its 50 offices with leased lines so that every office can reach every other one, directly or through other offices, and it wants the smallest total lease cost. Which technique fits?

  1. Dijkstra's algorithm from the headquarters, keeping the lines of every cheapest route
  2. BFS from the headquarters
  3. A minimum spanning tree, built with Kruskal's algorithm
  4. A topological sort of the offices
Show the answer

C. A minimum spanning tree, built with Kruskal's algorithm

The goal is the cheapest total set of lines that connects everyone, which is exactly a minimum spanning tree. Dijkstra minimizes each office's route from the headquarters, a different goal whose lines can cost more in total.

Optimized lessonWhat you will do there
Graphs, BFS & DFSProve that BFS computes distances, use DFS's discovery and finishing times to classify edges, find components and cycles, and test whether a graph is bipartite.
DAGs, Topological Sort & Strong ConnectivityProve when a topological order exists, run Kahn's algorithm and DFS finishing order, split a directed graph into strongly connected components, and do dynamic programming on DAGs.
Shortest Paths: Dijkstra, Bellman–Ford, Floyd–WarshallProve Dijkstra's algorithm correct, handle negative edges and detect negative cycles, and compute the distances between all pairs.
Minimum Spanning Trees & Union-FindProve the cut property with an exchange argument, run Kruskal's and Prim's algorithms, and make union-find nearly constant-time.
Network Flow & MatchingFind maximum flows with augmenting paths, prove the max-flow min-cut theorem, and solve bipartite matching as a flow problem.
In the Optimized lessons, each algorithm gets its code, a proof that it is correct, and its exact running time.

Key takeaways

  • A graph is a set of vertices joined by edges, directed or undirected, weighted or not. Store it as adjacency lists, with memory proportional to n+mn + m, unless it is small and dense.
  • BFS explores in layers with a queue and finds the paths with the fewest edges; DFS dives deep with a stack or recursion. Both visit everything reachable from the start.
  • Grids, mazes and puzzles are graphs whose edges are generated on the fly, and one flood fill per region counts the connected components.
  • A topological order exists exactly when the dependencies have no cycle; Kahn's algorithm finds one by repeatedly removing a task whose prerequisites are all done.
  • With non-negative costs, Dijkstra's algorithm finds cheapest routes by settling vertices from nearest to farthest. Kruskal's algorithm builds a minimum spanning tree from the cheapest edges that close no cycle.
  • Read the signals: fewest steps → BFS; prerequisites → topological sort; cheapest route → Dijkstra; connect everything cheaply → minimum spanning tree; merging groups → union-find; maximum throughput or pairing → flow and matching.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A road map has 10 million intersections, each joined to at most 4 others. How should a program store it?

  1. As an adjacency matrix, because it answers "are uu and vv joined?" in one step
  2. As adjacency lists, with at most 4×1074 \times 10^7 entries in total
  3. Either way: both need about the same memory
  4. As a list of every possible route
Show the answer

B. As adjacency lists, with at most 4×1074 \times 10^7 entries in total

Each intersection's list has at most 4 entries, so the lists hold at most 4×1074 \times 10^7 entries in total. A matrix needs (107)2=1014(10^7)^2 = 10^{14} cells, almost all of them empty: about 12 terabytes even at one bit per cell.

Question 2

In an undirected graph, A is joined to B and C, B is joined to D, and C is joined to D and E. Taking neighbors in alphabetical order, in which order does BFS from A visit the vertices?

  1. A, B, D, C, E
  2. A, B, C, E, D
  3. A, B, C, D, E
  4. A, D, B, C, E
Show the answer

C. A, B, C, D, E

BFS from A discovers B and C (distance 1). Dequeuing B discovers D; dequeuing C discovers E, since D is already known. So the vertices at distance 2 come out in the order they were discovered: A, B, C, D, E.

Question 3

Kahn's algorithm stops with some tasks never output. What does that prove about the dependencies?

  1. They contain a loop of tasks that each wait for the next, so no valid order exists
  2. The algorithm started from the wrong task
  3. Some task has more than two prerequisites
  4. The graph is not connected
Show the answer

A. They contain a loop of tasks that each wait for the next, so no valid order exists

Every leftover task still waits for another leftover task. Following those waits backward must eventually repeat a task, which closes a directed cycle, and the tasks of a cycle can never be ordered, since each must come before the next.

Question 4

With non-negative weights, in what order does Dijkstra's algorithm settle the vertices?

  1. In the order in which they were discovered
  2. By the number of edges between them and the source
  3. Alphabetically
  4. In order of increasing distance from the source
Show the answer

D. In order of increasing distance from the source

Each round settles the unsettled vertex with the smallest tentative distance, and with non-negative weights that distance is final. So vertices are settled from nearest to farthest: on the city map, A 0, C 2, B 3, D 5, G 7, F 8, E 9 and H 10.

Question 5

When does Kruskal's algorithm skip an edge?

  1. When it is heavier than the previous edge it took
  2. When its two ends are already connected by edges it has taken
  3. When one of its ends already touches an edge it has taken
  4. When its weight is above the average weight
Show the answer

B. When its two ends are already connected by edges it has taken

Such an edge would close a cycle, and a spanning tree has none. Every other edge joins two separate groups, and Kruskal takes it because it is the cheapest edge left that does so.

Go deeper

Further reading

  • R. Sedgewick & K. Wayne, Algorithms, 4th ed. (Addison-Wesley, 2011), chapter 4, "Graphs".
  • J. Erickson, Algorithms (2019), chapters 5–11, free online at jeffe.cs.illinois.edu.