A graph is a set of things (nodes, also called vertices) and connections between them (edges). Cities and roads, people and friendships, courses and prerequisites: all graphs. A tree is a special graph; a general graph can have cycles and has no root.
The words you'll see
| Word | Meaning |
|---|---|
| undirected | edges go both ways (friendship: if A knows B, B knows A) |
| directed | edges have a direction (b → a: "b must come before a") |
| neighbors | the nodes directly connected to a node |
| cycle | a path that comes back to where it started |
| connected component | a group of nodes all reachable from each other, cut off from the rest |
V and E | the number of nodes (vertices) and edges, used in complexities |
How graphs are given to you
Problems describe graphs in a few ways. Your first step is often converting to an adjacency list: for each node, the list of its neighbors.
A list of edges → build the adjacency list yourself:
const neighbors = Array.from({ length: n }, () => [])
for (const [a, b] of edges) {
neighbors[a].push(b)
neighbors[b].push(a) // undirected: both directions
}A grid → each cell is a node, and its neighbors are the cells up, down, left and right (Number of Islands, Pacific Atlantic Water Flow).
Node objects → each node holds its own neighbors list (Clone Graph).
Visiting a graph: DFS and BFS
Both visit every node reachable from a start. The one rule that's new compared with trees: keep a visited set, or cycles will make you go round forever.
DFS (depth-first) with a stack:
const visited = new Set([start])
const stack = [start]
while (stack.length > 0) {
const node = stack.pop()
for (const next of neighbors[node]) {
if (!visited.has(next)) {
visited.add(next) // mark when you PUSH, so nothing is pushed twice
stack.push(next)
}
}
}BFS (breadth-first) is the same with a queue instead of a stack: it visits nodes in order of distance from the start, so it finds shortest paths (by number of edges).
The patterns in this category
Counting groups: connected components
Loop over every node; each unvisited one starts a new component: count it and visit everything reachable from it (Number of Islands, Number of Connected Components).
Copying with a map
Map each original node to its copy; the map doubles as the visited set (Clone Graph).
Searching backward from the targets
When many starts share a few destinations, search from the destinations instead (Pacific Atlantic Water Flow).
Ordering with dependencies: topological sort
In a directed graph of "must come before" edges, repeatedly take a node with no remaining prerequisites (in-degree 0). If you can't take them all, there's a cycle (Course Schedule).
Union-Find
A small structure that tracks groups and merges them quickly:
const parent = Array.from({ length: n }, (_, i) => i) // everyone is their own group
function find(x) {
while (parent[x] !== x) {
parent[x] = parent[parent[x]] // path compression
x = parent[x]
}
return x // the group's representative
}
// to connect a and b: parent[find(a)] = find(b)If an edge's two ends already have the same representative, that edge closes a cycle (Graph Valid Tree).
How fast is it?
Visiting a graph touches each node and each edge a constant number of times: O(V + E). For a grid with m × n cells, that's O(m · n).
How to recognize this category
- Things connected to other things: maps, networks, dependencies, grids where you move between cells.
- "How many groups / islands / regions?" → connected components.
- "Can all of these be done in some order?" → cycle detection / topological sort.
- "Shortest number of steps" → BFS.
Common mistakes
- No
visitedset. Cycles make the search loop forever. - Marking visited when popping instead of when pushing. Nodes get pushed many times.
- Undirected edges added in one direction only.
- Deep recursion on big grids. A 300×300 grid can need 90,000 nested calls; an explicit stack avoids overflowing the call stack.