v9.1.1
Menu

Chapter 7: Graphs

Week 7

Master graph fundamentals from representations to traversals. Learn BFS and DFS on graphs, grid-based graph problems, and classic interview patterns like flood fill, number of islands, and word ladder.

Topics
8
Demos
5
Videos
3
Min read
47

Chapter Overview

Graphs are one of the most versatile data structures in computer science. Unlike trees, which are hierarchical and acyclic, graphs can represent arbitrary relationships between entities --- social networks, road maps, web pages, dependency chains, and much more.

A graph consists of vertices (nodes) and edges (connections between nodes). Edges can be directed or undirected, weighted or unweighted. The way you represent and traverse a graph determines the efficiency of your solution.

This chapter builds your graph intuition from the ground up:

  • Graph Fundamentals: Representations, terminology, and when to use each
  • BFS & DFS on Graphs: Adapting tree traversals to handle cycles and disconnected components
  • Shortest Path: Finding minimum-hop paths in unweighted graphs
  • Grid as Graph: Treating 2D matrices as implicit graphs
  • Classic Problems: Flood fill, number of islands, and word ladder

Chapter Roadmap

Click any topic to jump in

Explainer videoInteractive demo
1
Graph Fundamentals

Vertices, edges, adjacency lists, and matrices — choosing the right representation for your data.

Vertices and EdgesAdjacency List RepresentationAdjacency Matrix Representation
Two core traversal strategies

Queue or stack

2
BFS on Graphs

Queue-based traversal with a visited set — handling cycles and disconnected components.

BFS with Visited SetLevel-Order Traversal on GraphsHandling Disconnected Components
3
DFS on Graphs

Recursive or stack-based deep exploration — finding connected components and cycles.

Recursive DFS with Visited SetIterative DFS with Explicit StackConnected Components via DFS
Using traversal to find distances
4
Shortest Path

BFS gives optimal distances in unweighted graphs — plus parent tracking for full path reconstruction.

BFS as Shortest Path AlgorithmPath Reconstruction with Parent Tracking
Implicit graphs in the wild

Grids and adjacency

5
Matrix as Graph

Grids as implicit graphs — each cell is a node, neighbors are the 4 or 8 adjacent cells.

Grid as Implicit GraphBoundary CheckingBFS and DFS on Grids
6
Flood Fill

Classic connectivity problem — BFS or DFS from a seed cell to fill a region.

The Flood Fill AlgorithmEarly Termination Check
Composite real-world problems

Islands and word ladders

7
Number of Islands

Count connected components in a grid — iterate, trigger BFS/DFS, mark visited.

Islands as Connected ComponentsIn-Place Marking vs Visited Set
8
Word Ladder

Words as nodes, one-letter changes as edges — BFS finds the shortest transformation sequence.

Words as Graph NodesBFS for Shortest Transformation

Topics

8 topics in this chapter

A delivery app needs routes between neighbourhoods, a social network records who knows whom, and a package manager records which library depends on which. None of these fits a tree. Roads loop back on themselves, friendships run both ways, and one library can be required by many others, so a node can have several parents or none.

The previous chapter, Breadth First Search, traversed trees, where every node has exactly one parent and no path returns to where it started. A graph drops both restrictions. It is just a set of vertices and a set of edges between them, and it may contain cycles, isolated vertices, and several separate pieces. Edges can be directed or undirected, weighted or unweighted, and each combination models a different kind of problem.

Before running any algorithm on a graph you have to store it, and the storage choice fixes the cost of every later step. We first set up the vocabulary of vertices, edges, and degrees. Then we compare the two standard representations, the adjacency list and the adjacency matrix, and see when each one wins.

Definition

A graph G=(V,E)G = (V, E) is a set of vertices VV and a set of edges EE, each edge joining a pair of vertices. Undirected edges are unordered pairs, directed edges ordered pairs. An adjacency list stores each vertex's neighbours in O(V+E)O(V + E) space; an adjacency matrix stores a V×VV \times V table of edge flags in O(V2)O(V^2) space.

In this topic

  1. 1Vertices and Edges
  2. 2Adjacency List Representation
  3. 3Adjacency Matrix Representation
1 of 3
Vertices and Edges

Before choosing an algorithm you must name the problem's objects and relationships. A vertex is an entity, such as a city, a user, or a course, and an edge joins two vertices. In an undirected graph an edge {u,v}\{u, v\} works both ways, like a two-way road; in a directed graph an edge (u,v)(u, v) goes from uu to vv only, like following someone online. The degree deg⁡(v)\deg(v) counts the edges touching vv, and directed graphs split it into in-degree and out-degree. Each undirected edge touches two endpoints, so degrees always sum to 2∣E∣2|E|, the handshaking lemma. Modelling a one-way relationship as undirected invents paths that do not exist.

Mathematical Intuition

A graph G=(V,E)G = (V, E) has ∣V∣=n|V| = n vertices and ∣E∣=m|E| = m edges. In an undirected graph, each edge {u,v}\{u, v\} contributes 11 to both deg⁡(u)\deg(u) and deg⁡(v)\deg(v), giving the handshaking lemma ∑v∈Vdeg⁡(v)=2∣E∣\sum_{v \in V} \deg(v) = 2|E|. In a directed graph, ∑vdeg⁡+(v)=∑vdeg⁡−(v)=∣E∣\sum_v \deg^+(v) = \sum_v \deg^-(v) = |E|. The maximum edge count is (n2)=n(n−1)2\binom{n}{2} = \frac{n(n-1)}{2} for a simple undirected graph (complete graph KnK_n) or n(n−1)n(n-1) for a directed one. Sparse graphs have m=O(n)m = O(n); dense graphs have m=Θ(n2)m = \Theta(n^2).

Example:

Given 4 cities connected as: A-B, B-C, C-D, A-D. How many vertices, edges, and what is the degree of each vertex?

2 of 3
Adjacency List Representation

Graph algorithms ask one question over and over: what are the neighbours of uu? An adjacency list answers it directly by storing, for each vertex, the list of vertices it connects to, usually a dict of lists or a list of lists indexed by vertex number. It uses O(V+E)O(V + E) space, where VV is the number of vertices and EE the number of edges; an undirected edge is stored twice, once in each endpoint's list. Listing the neighbours of uu costs O(deg⁡(u))O(\deg(u)), which is optimal, but testing whether one specific edge exists means scanning a list. Most interview graphs are sparse, with EE far below V2V^2, so this is the default.

Mathematical Intuition

An adjacency list stores nn vertex entries, each mapping to a list of neighbors. Total space is O(n+m)O(n + m): each vertex contributes O(1)O(1) overhead, and each edge appears in 1 or 2 lists (directed or undirected). Checking whether edge (u,v)(u, v) exists requires scanning uu's neighbor list — O(deg⁡(u))O(\deg(u)) worst case. Iterating all neighbors of uu is O(deg⁡(u))O(\deg(u)), which is optimal. For sparse graphs with m=O(n)m = O(n), total space is O(n)O(n), making adjacency lists dramatically more efficient than matrices.

Example:

Represent this undirected graph as an adjacency list: edges are (0,1), (0,2), (1,3), (2,3).

3 of 3
Adjacency Matrix Representation

When a problem repeatedly asks whether two particular vertices are connected, scanning lists is slow. An adjacency matrix is a V×VV \times V array AA with A[i][j]=1A[i][j] = 1 when an edge runs from ii to jj and 0 otherwise; weighted graphs store the weight instead. An edge test is a single O(1)O(1) lookup, and an undirected graph gives a symmetric matrix. The costs are O(V2)O(V^2) space however few edges exist, and O(V)O(V) time to list one vertex's neighbours, because the whole row must be read. For 100,000 vertices that is 10 billion cells even when most are zero, so matrices suit small or dense graphs.

Mathematical Intuition

An n×nn \times n adjacency matrix AA has A[i][j]=1A[i][j] = 1 if edge (i,j)(i, j) exists. Space is always O(n2)O(n^2) regardless of mm. Edge existence queries are O(1)O(1), but iterating the neighbors of vertex ii is O(n)O(n) — you must scan the entire row. The matrix is symmetric (A=ATA = A^T) for undirected graphs. Matrix powers have elegant meaning: Ak[i][j]A^k[i][j] counts walks of length kk from ii to jj. For dense graphs with m=Θ(n2)m = \Theta(n^2), matrices and lists use the same space, but matrices give O(1)O(1) edge lookups.

Example:

Build an adjacency matrix for 4 vertices with edges: (0,1), (0,2), (1,3), (2,3).