Lesson 141 of 296
Graphs: adjacency lists, BFS and DFS
What you will learn
- Graph vocabulary
- Representing graphs: adjacency lists and matrices
- BFS and DFS on graphs, with visited sets
- Number of Islands
- Clone Graph
- Rotting Oranges (multi-source BFS)
On this page
What is a graph?
A graph is a set of nodes (also called vertices) connected by edges. Trees are a special kind of graph. Graphs model networks: friends on social media, roads between cities, links between web pages, dependencies between tasks.
| Word | Meaning |
|---|---|
| Directed | Edges have a direction (A → B is not B → A), like "follows" on social media |
| Undirected | Edges go both ways, like friendship |
| Weighted | Edges have a cost, like distance or time |
| Cycle | A path that returns to its start |
| Connected component | A group of nodes all reachable from each other |
| Neighbours | The nodes directly connected to a node |
Representing a graph
Adjacency list (most common): a Map from each node to its neighbours.
function buildAdjacencyList(n: number, edges: [number, number][], directed = false): number[][] {
const graph: number[][] = Array.from({ length: n }, () => []);
for (const [from, to] of edges) {
graph[from]!.push(to);
if (!directed) graph[to]!.push(from);
}
return graph;
}Space O(V + E) for V nodes and E edges.
Adjacency matrix: an n × n grid where matrix[a][b] is 1 if there is an edge. O(V²) space; only good for small, dense graphs.
Grids are graphs too: each cell is a node, and its up/down/left/right cells are its neighbours (Lesson 119).
The visited set
Unlike trees, graphs can have cycles. Without remembering which nodes you have visited, DFS or BFS can loop forever. Always keep a visited Set (or mark cells in a grid).
DFS and BFS on a graph
function dfsGraph(graph: number[][], start: number): number[] {
const visited = new Set<number>();
const order: number[] = [];
function visit(node: number): void {
if (visited.has(node)) return;
visited.add(node);
order.push(node);
for (const neighbour of graph[node]!) visit(neighbour);
}
visit(start);
return order;
}
function bfsGraph(graph: number[][], start: number): number[] {
const visited = new Set<number>([start]);
const queue: number[] = [start];
for (let head = 0; head < queue.length; head++) {
const node = queue[head]!;
for (const neighbour of graph[node]!) {
if (!visited.has(neighbour)) {
visited.add(neighbour);
queue.push(neighbour);
}
}
}
return queue;
}In BFS, mark nodes as visited when you add them to the queue, not when you take them out; otherwise the same node can be queued many times.
Both are O(V + E) time.
BFS finds the shortest path (fewest edges) in an unweighted graph, because it explores in rings of increasing distance.
Number of Islands
Problem (LeetCode 200): a grid of "1" (land) and "0" (water). Count the islands (groups of land connected up, down, left or right).
Idea: scan every cell. When you find unvisited land, that is a new island: count it, then flood the whole island (DFS or BFS) marking its cells as visited, so they are not counted again.
function numIslands(grid: string[][]): number {
const rows = grid.length;
const cols = grid[0]?.length ?? 0;
let islands = 0;
function sink(r: number, c: number): void {
const stack: [number, number][] = [[r, c]];
grid[r]![c] = "0";
while (stack.length > 0) {
const [cr, cc] = stack.pop()!;
for (const [dr, dc] of DIRECTIONS) {
const nr = cr + dr;
const nc = cc + dc;
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr]![nc] === "1") {
grid[nr]![nc] = "0";
stack.push([nr, nc]);
}
}
}
}
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (grid[r]![c] === "1") {
islands++;
sink(r, c);
}
}
}
return islands;
}This uses an explicit stack (iterative DFS), so large islands cannot overflow the call stack, and marks land as "0" instead of keeping a visited set (ask if changing the input is allowed). O(rows × cols) time. DIRECTIONS is the list from Lesson 119.
Clone Graph
Problem (LeetCode 133): make a deep copy of a connected undirected graph given one node.
Idea: traverse the graph, keeping a Map from original node → its copy. The Map is also the visited set, and it handles cycles (same idea as deep clone, Lesson 80).
class GraphNode {
val: number;
neighbors: GraphNode[];
constructor(val: number, neighbors: GraphNode[] = []) {
this.val = val;
this.neighbors = neighbors;
}
}
function cloneGraph(node: GraphNode | null): GraphNode | null {
if (node === null) return null;
const copies = new Map<GraphNode, GraphNode>();
function clone(original: GraphNode): GraphNode {
const existing = copies.get(original);
if (existing) return existing;
const copy = new GraphNode(original.val);
copies.set(original, copy);
for (const neighbour of original.neighbors) {
copy.neighbors.push(clone(neighbour));
}
return copy;
}
return clone(node);
}Store the copy in the Map before visiting neighbours, so a cycle back to this node finds the copy. O(V + E).
Rotting Oranges
Problem (LeetCode 994): a grid has 0 (empty), 1 (fresh orange), 2 (rotten). Every minute, fresh oranges next to rotten ones become rotten. How many minutes until none are fresh? Return -1 if impossible.
Idea: multi-source BFS. Start BFS from all rotten oranges at once (they are all at distance 0). Each BFS level is one minute.
function orangesRotting(grid: number[][]): number {
const rows = grid.length;
const cols = grid[0]?.length ?? 0;
let fresh = 0;
let current: [number, number][] = [];
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (grid[r]![c] === 2) current.push([r, c]);
else if (grid[r]![c] === 1) fresh++;
}
}
let minutes = 0;
while (current.length > 0 && fresh > 0) {
const next: [number, number][] = [];
for (const [r, c] of current) {
for (const [dr, dc] of DIRECTIONS) {
const nr = r + dr;
const nc = c + dc;
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr]![nc] === 1) {
grid[nr]![nc] = 2;
fresh--;
next.push([nr, nc]);
}
}
}
current = next;
minutes++;
}
return fresh === 0 ? minutes : -1;
}O(rows × cols). Multi-source BFS also solves "distance to the nearest exit / gate / zero" problems.
How to say it in an interview
"I represent graphs with an adjacency list, O(V plus E) space, and treat grids as graphs with four neighbours. Because graphs can have cycles, I always track visited nodes, marking them when enqueued in BFS. DFS and BFS are both O(V plus E); BFS gives the shortest path in an unweighted graph. Number of Islands counts each new land cell and flood-fills its island. Clone Graph keeps a map from original to copy that doubles as the visited set. Rotting Oranges is a multi-source BFS where each level is one minute."
Key words
| Word | Meaning |
|---|---|
| Graph | Nodes connected by edges |
| Vertex / edge | A node / a connection |
| Directed / undirected | One-way / two-way edges |
| Weighted | Edges with a cost |
| Adjacency list | A list of neighbours for each node |
| Visited set | Nodes already explored, to avoid loops |
| Flood fill | Visiting every cell of a connected region |
| Multi-source BFS | BFS starting from several nodes at once |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.