Skip to main content
Back to all problems
Beginner guide, Algorithms & data structures

Graphs

DFS and BFS on graphs and grids, cycle detection, and Union-Find.

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

WordMeaning
undirectededges go both ways (friendship: if A knows B, B knows A)
directededges have a direction (b → a: "b must come before a")
neighborsthe nodes directly connected to a node
cyclea path that comes back to where it started
connected componenta group of nodes all reachable from each other, cut off from the rest
V and Ethe 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:

js
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:

js
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:

js
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 visited set. 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.

Practice what you learned

The problems go from easier to harder. Try each one on your own and open a hint when you get stuck.