PIXELBANKv8.2.1
Menu
Back to DSA Study Plan
Week 7

Chapter 7: Graphs

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.

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

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

A graph G=(V,E)G = (V, E) consists of a set of vertices VV and a set of edges EE. Each edge connects two vertices. Graphs come in many flavors --- directed vs undirected, weighted vs unweighted, cyclic vs acyclic --- and picking the right representation is the first step to solving any graph problem.

The two primary representations are the adjacency list (space-efficient for sparse graphs) and the adjacency matrix (fast edge lookups for dense graphs). Most interview problems use adjacency lists because real-world graphs tend to be sparse.

In this topic

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

A vertex (or node) represents an entity, and an edge represents a relationship between two entities. In an undirected graph, edges have no direction --- if A connects to B, then B connects to A. In a directed graph (digraph), edges point from one vertex to another --- A pointing to B does not imply B points to A.

The degree of a vertex is the number of edges connected to it. In directed graphs, we distinguish in-degree (edges coming in) and out-degree (edges going out).

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 vVdeg(v)=2E\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(n1)2\binom{n}{2} = \frac{n(n-1)}{2} for a simple undirected graph (complete graph KnK_n) or n(n1)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

An adjacency list stores, for each vertex, a list of its neighbors. This is typically implemented as a dictionary (hash map) where each key is a vertex and the value is a list of adjacent vertices.

Space complexity: O(V+E)O(V + E) --- stores each vertex and each edge once (twice for undirected). Edge lookup: O(degree)O(\text{degree}) --- must scan the neighbor list. Best for: Sparse graphs where EV2E \ll V^2.

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

An adjacency matrix is a 2D array of size V×VV \times V where entry [i][j]=1[i][j] = 1 if there is an edge from vertex ii to jj, and 00 otherwise. For weighted graphs, the entry stores the edge weight.

Space complexity: O(V2)O(V^2) regardless of edge count. Edge lookup: O(1)O(1) --- just check the matrix cell. Best for: Dense graphs where EV2E \approx V^2, or when you need fast edge existence checks.

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).