Skip to main content
Quick Reference

Graphs Cheatsheet

A graph on one page — lists, searches, and the traps around visited marks, negative weights, and directed cycles.

10 sections 10 tables 14 code snippets

Vertices and edges

Undirected, both ways

graph[u].append(v)
graph[v].append(u)

Directed, one way

graph[u].append(v)

The parts

IdeaMeaning
VertexA node. n counts every vertex, including isolates
Undirected edgeA link both ways. Store it twice in a list
Directed edgeOne way. You can walk only to the out-neighbors
DegreeUndirected: incident edges. The degrees sum to twice the edge count
Out-degreeEdges that leave. The out-degrees sum to the edge count
PathNo repeated vertex. A cycle returns to a vertex already on the path

This page is a graph. Network flow is left out.

How the edges are stored

Sparse graphs prefer a list

# a list uses O(n + m) space

List, matrix, or edge list

StoreCost
Adjacency listSpace O(n + m). Walking the neighbors of u is O(degree of u)
Adjacency matrixSpace O(n * n). An edge check is O(1). Empty slots still take space
Undirected matrixSymmetric. Set both [u][v] and [v][u]
Edge listSpace O(m). The neighbors of one vertex require a scan of every edge
Weighted listEach neighbor is a pair (v, w)
Missing vertexA list built only from edges drops an isolate, so n is too small

Breadth-first search

Mark it, then enqueue it

seen.add(node)
dq.append(node)

A queue, fewest edges first

RuleMeaning
QueueThe first vertex in is the first one out
Mark on enqueueA vertex sits in the queue once. Marking on dequeue lets copies pile up
Unweighted distanceThe first visit is the fewest edges from the source
One componentA vertex with no path from the source stays unseen
TimeO(n + m) on a list. Scanning a matrix is O(n * n)
GridMark the cell when you enqueue it, or every neighbor queues it again

Depth-first search

Gray is still on the path

# gray means the vertex is still on the stack

Three colors

ColorMeaning
WhiteNot seen yet
GrayOn the current path from the start of this search
BlackFinished. Every descendant is done
Directed cycleAn edge into a gray vertex
TimeO(n + m) on a list. A chain can exceed the default recursion limit of about 1000 frames
KosarajuDFS for finish order, then DFS on the reversed edges from the latest finish. Each tree is one strong component

Where a cycle shows up

Ignore the parent

# undirected: a visited neighbor is a cycle only if it is not the parent

Directed and undirected differ

GraphCycle test
UndirectedA visited neighbor that is not the parent
DirectedA gray vertex, still on the stack. A black vertex is already finished
Self-loopA directed edge from a vertex to itself is a cycle
TreeConnected, undirected, no cycle, and exactly n - 1 edges
ComponentsEach new search start in an undirected graph is another component
StrongA directed path both ways between every pair in the set

Shortest paths

Keep a strictly better distance

if dist[u] + w < dist[v]:
    dist[v] = dist[u] + w

Hops are not weights

# BFS distance counts edges, not weights

Match the algorithm to the weights

AlgorithmWhen
BFSEvery edge has the same weight. Distance is a hop count
0-1 BFSWeights are only 0 or 1. A 0-edge goes to the front of a deque, a 1-edge to the back. Settle a vertex the first time it leaves
DijkstraEvery weight is >= 0. The first time you pop a vertex, its distance is final
Binary heapO((n + m) log n) with pairs of distance and vertex
Stale entryA later pop with a worse distance is skipped
Negative weightPop-is-final is false. Use Bellman-Ford

Negative weights

One pass per vertex, almost

# relax every edge, and do that n - 1 times

Bellman-Ford and a DAG

RuleMeaning
RelaxIf dist[u] + w is smaller than dist[v], write that sum into dist[v]
RoundsRelax every edge once per round, for n - 1 rounds
Extra roundIf an edge still relaxes, a negative cycle is reachable from the source
UnreachableSkip an edge whose start was never reached. A big sentinel plus a negative weight can look like a real distance
DAGTopo order, then relax each edge once. Negative weights are allowed because there is no cycle
TimeBellman-Ford is O(n * m)

Topological order

A neighbor just lost its last incoming edge

if indeg[nxt] == 0:
    dq.append(nxt)

Only a DAG has this order

RuleMeaning
DAG onlyA directed cycle means no topological order
KahnStart the queue with every vertex whose in-degree is 0
RemoveDrop the vertex, and decrement the in-degree of each neighbor
New zeroA neighbor that hits 0 joins the queue
Too fewIf the output has fewer than n vertices, the graph has a cycle
DFS wayAppend a vertex after its neighbors, then reverse the list

A minimum spanning tree

Skip an edge inside one set

# the same root means skip this edge

Lightest set of edges that stays connected

RuleMeaning
UndirectedKruskal and Prim need an undirected graph
KruskalSort edges lightest first. Add the edge when its ends sit in different sets
Union-findThe same root means the edge would close a cycle, so skip it
n - 1 edgesA connected graph stops there. Fewer edges means a forest
PrimGrow one set. The key is the cheapest edge into the set, not the path distance from a source
Not a shortest-path treeAn MST minimizes the total weight. It does not minimize each path from one source

Interview traps

The way back is missing

# one append on an undirected edge hides the way back

Final too early

# a negative weight breaks Dijkstra

Finished is not a back edge

# a black vertex is not a directed cycle

Traps worth memorising

TrapWhat happensPrefer
One append for an undirected edgeThe walk cannot returnAppend both directions
Mark on dequeueOne vertex is queued many timesMark it when it is enqueued
Any visited vertex is a directed cycleA finished vertex is not a back edgeGray, still on the stack
Dijkstra and a negative edgeA vertex can be finalized too earlyBellman-Ford
BFS on weighted edgesThe hop count ignores the weightsDijkstra when weights differ and stay non-negative
Heap tie on a node objectPython 3 raises TypeError when distances matchPut an int id in the heap pair

How to use this page: store an undirected edge both ways, mark a vertex when you enqueue it, and use Bellman-Ford when a weight can be negative.