Graphs (DSA Core #6)
Almost every graph problem is one of five things: reach everything (BFS/DFS), order the work (topological sort), find the cheapest route (shortest paths), pick the cheapest wiring (MST), or group things that are mutually reachable (SCC). Each has one standard implementation and one complexity sentence that you should be able to say without thinking.
Terminology, and the two axes that matter
- Directed edges have a direction; undirected edges do not.
- Weighted edges carry a cost; unweighted means every edge costs 1.
- Degree of a vertex is the number of incident edges. In a directed graph, in-degree and out-degree are separate.
- Path: a sequence of edges. Simple path: no repeated vertex.
- Cycle: a path that returns to its start.
- Connected: every pair of vertices has a path (undirected). Strongly connected: every pair reaches each other (directed).
- Dense graph: \(E \approx V^2\). Sparse: \(E \approx V\).
Two identities worth memorizing: the sum of degrees is \(2E\) (each edge counted twice), and a connected graph with \(V\) vertices needs at least \(V-1\) edges — a tree has exactly that and any extra edge creates a cycle.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
n/.style={draw, thick, circle, minimum size=0.62cm, font=\scriptsize\bfseries},
a/.style={->, thick}]
\node[n] (a) at (0,0) {A};
\node[n] (b) at (1.6,0) {B};
\node[n] (c) at (0.8,-1.2) {C};
\node[n] (d) at (2.6,-1.2) {D};
\draw[a] (a) -- (b);
\draw[a] (a) -- (c);
\draw[a, bend left=18] (b) to (c);
\draw[a] (c) -- (d);
\draw[a] (b) -- (d);
\node[font=\scriptsize, anchor=north] at (1.3,-1.6) {directed, unweighted, 4 edges};
\end{tikzpicture}
ASolution
No. A tree on 10 vertices has exactly 9 edges. 15 edges force at least 6 independent cycles.
Representations: adjacency list versus matrix
The adjacency matrix is a \(V \times V\) boolean (or weight) table: adj[u][v]
answers “is there an edge” in \(O(1)\), and iterating a vertex’s neighbours costs
\(O(V)\). The adjacency list stores only existing edges: iterating neighbours costs
\(O(\deg(u))\), but “is there an edge” costs \(O(\deg(u))\).
// list: the default
vector<vector<int>> adj(n);
adj[u].push_back(v);
adj[v].push_back(u); // only for undirected
// weighted list
vector<vector<pair<int,int>>> wadj(n); // {neighbour, weight}
wadj[u].push_back({v, w});
// matrix
vector<vector<long long>> mat(n, vector<long long>(n, INF));
mat[u][v] = w;
| Adjacency list | Adjacency matrix | |
|---|---|---|
| Space | \(O(V+E)\) | \(O(V^2)\) |
| Neighbour iteration | \(O(\deg(u))\) | \(O(V)\) |
| Edge lookup | \(O(\deg(u))\) | \(O(1)\) |
| Best for | sparse graphs, most OAs | dense graphs, Floyd–Warshall |
For \(V = 10^5\) and \(E = 2 \times 10^5\), a matrix needs \(10^{10}\) entries — 40 GB. The list needs about 200k integers. That choice is not stylistic.
An edge list (vector<tuple<int,int,int>>) is the right representation for
Kruskal and Bellman–Ford, which iterate all edges instead of neighbours.
matrix comfortably?
ASolution
\(5000^2 = 25\) million entries. With long long that is 200 MB, and the
\(O(V^2)\) initialization alone is expensive. A list with \(E \ll V^2\) is smaller.
BFS and DFS
Both traverse a component in \(O(V+E)\). BFS uses a queue and visits by distance. DFS uses a stack or recursion and follows one branch to the end.
vector<int> bfs(int s, const vector<vector<int>>& adj) {
vector<int> dist(adj.size(), -1);
queue<int> q;
dist[s] = 0;
q.push(s);
while (!q.empty()) {
int u = q.front(); q.pop();
for (int v : adj[u]) {
if (dist[v] != -1) continue;
dist[v] = dist[u] + 1;
q.push(v);
}
}
return dist;
}
BFS on an unweighted graph gives shortest paths in edges, because the queue processes vertices in non-decreasing distance order. That property is the reason BFS exists; DFS gives no such guarantee.
void dfs(int u, const vector<vector<int>>& adj, vector<bool>& seen) {
seen[u] = true;
for (int v : adj[u])
if (!seen[v]) dfs(v, adj, seen);
}
Recursive DFS on \(10^5\) vertices can overflow the stack. Use an explicit stack:
void dfsIter(int s, const vector<vector<int>>& adj, vector<bool>& seen) {
vector<int> st{s};
while (!st.empty()) {
int u = st.back(); st.pop_back();
if (seen[u]) continue;
seen[u] = true;
for (int v : adj[u]) if (!seen[v]) st.push_back(v);
}
}
Mark on push or on pop — but be consistent. Marking only on pop lets duplicates into the stack and can blow up to \(O(E)\) entries (usually fine, occasionally not).
\begin{tikzpicture}[font=\rmfamily, >=stealth,
n/.style={draw, thick, circle, minimum size=0.62cm, font=\scriptsize\bfseries}]
\node[n, fill=green!30] (s) at (0,0) {S};
\node[n, fill=blue!18] (a) at (-1.2,-0.9) {A};
\node[n, fill=blue!18] (b) at (1.2,-0.9) {B};
\node[n, fill=orange!25] (c) at (-1.8,-1.8) {C};
\node[n, fill=orange!25] (d) at (0,-1.8) {D};
\draw[thick] (s) -- (a); \draw[thick] (s) -- (b);
\draw[thick] (a) -- (c); \draw[thick] (a) -- (d);
\draw[thick] (b) -- (d);
\node[font=\scriptsize, anchor=west] at (2.2,-0.3) {layer 0: S};
\node[font=\scriptsize, anchor=west] at (2.2,-0.8) {layer 1: A, B};
\node[font=\scriptsize, anchor=west] at (2.2,-1.3) {layer 2: C, D};
\end{tikzpicture}
ASolution
It expands vertices in order of edge count. With weights, “fewer edges” does not mean “cheaper”, so the first visit is not necessarily the shortest distance.
Connected components
Run BFS/DFS from every unvisited vertex; each launch is one component.
int components(const vector<vector<int>>& adj) {
int n = (int)adj.size(), count = 0;
vector<bool> seen(n, false);
for (int i = 0; i < n; ++i) {
if (seen[i]) continue;
++count;
queue<int> q; q.push(i); seen[i] = true;
while (!q.empty()) {
int u = q.front(); q.pop();
for (int v : adj[u]) if (!seen[v]) { seen[v] = true; q.push(v); }
}
}
return count;
}
Grid problems are the same traversal with four (or eight) implicit neighbours. Number of islands, flood fill, and “max area” are all component counting.
On a directed graph, “reachable from” is not symmetric, so components split into weakly connected (ignoring direction) and strongly connected (both directions). SCCs are below.
ASolution
Each land cell is a vertex, adjacency is 4-directional, and each component is one island. The count is the number of BFS/DFS launches.
Cycle detection
Undirected. DFS and reject an already-visited neighbour that is not the parent. With parallel edges, track the edge id instead of the parent.
bool hasCycleU(int u, int parent, const vector<vector<int>>& adj,
vector<bool>& seen) {
seen[u] = true;
for (int v : adj[u]) {
if (v == parent) continue;
if (seen[v]) return true;
if (hasCycleU(v, u, adj, seen)) return true;
}
return false;
}
Directed. A cycle exists exactly when DFS reaches a vertex on the current recursion stack (grey). Colours: 0 unvisited, 1 in progress, 2 done.
bool hasCycleD(int u, const vector<vector<int>>& adj, vector<int>& color) {
color[u] = 1;
for (int v : adj[u]) {
if (color[v] == 1) return true;
if (color[v] == 0 && hasCycleD(v, adj, color)) return true;
}
color[u] = 2;
return false;
}
The colour version is the same as topological sorting by DFS: a graph is a DAG iff the DFS has no back edge. DSU detects undirected cycles on the fly (an edge joining two already-connected vertices closes a cycle) and cannot detect directed cycles.
directed one?
ASolution
In an undirected graph, any edge back to a visited vertex closes a loop. In a directed graph, two paths can reach the same vertex without forming a cycle, so you must detect an edge into the current recursion stack.
Topological sorting and DAGs
A topological order lists vertices so every edge points forward. It exists iff the graph is a DAG. Kahn’s algorithm is BFS on in-degree:
vector<int> topoOrder(int n, const vector<vector<int>>& adj, vector<int> indeg) {
queue<int> q;
for (int i = 0; i < n; ++i) if (indeg[i] == 0) q.push(i);
vector<int> order;
while (!q.empty()) {
int u = q.front(); q.pop();
order.push_back(u);
for (int v : adj[u]) if (--indeg[v] == 0) q.push(v);
}
return order; // order.size() < n means a cycle
}
The DFS version pushes a vertex after all its descendants and reverses the result. Same \(O(V+E)\), but Kahn’s gives you the cycle check for free and the lexicographically smallest order with a priority queue instead of a queue.
Applications: build order, course scheduling, dependency resolution, DP on DAGs (Ch. 7), and SCC condensation. If a problem says “prerequisites” or “before”, it is a topological sort.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
n/.style={draw, thick, minimum width=1.0cm, minimum height=0.55cm, font=\scriptsize},
a/.style={->, thick}]
\node[n] (a) at (0,0) {A};
\node[n] (b) at (1.4,0) {B};
\node[n] (c) at (2.8,0) {C};
\draw[a] (a) -- (b);
\draw[a] (b) -- (c);
\draw[a, bend left=22] (a) to (c);
\node[font=\scriptsize, anchor=north] at (1.4,-0.45) {order: A, B, C};
\end{tikzpicture}
ASolution
A vertex on a cycle never reaches in-degree 0, so it never enters the queue. If
the produced order has fewer than n vertices, a cycle exists.
Shortest paths
Unweighted: BFS. Already covered; dist is the number of edges.
Non-negative weights: Dijkstra. Repeatedly settle the closest unsettled vertex. With a binary heap the cost is \(O((V+E)\log V)\).
vector<long long> dijkstra(int s, const vector<vector<pair<int,int>>>& adj) {
const long long INF = LLONG_MAX / 4;
vector<long long> dist(adj.size(), INF);
priority_queue<pair<long long,int>,
vector<pair<long long,int>>, greater<>> pq;
dist[s] = 0;
pq.push({0, s});
while (!pq.empty()) {
auto [d, u] = pq.top(); pq.pop();
if (d != dist[u]) continue; // stale heap entry
for (auto [v, w] : adj[u]) {
if (d + w < dist[v]) {
dist[v] = d + w;
pq.push({dist[v], v});
}
}
}
return dist;
}
The d != dist[u] check is not optional. C++ has no decrease-key, so old entries
stay in the heap and must be skipped. Without the check the algorithm is still
correct but does extra work.
Dijkstra fails on negative edges. The greedy settle assumes no later path can be cheaper, and a negative edge breaks that. Use Bellman–Ford.
Any weights, detect negative cycles: Bellman–Ford. Relax all edges \(V-1\) times; one more pass detects a negative cycle.
bool bellmanFord(int n, int s, const vector<array<int,3>>& edges,
vector<long long>& dist) {
const long long INF = LLONG_MAX / 4;
dist.assign(n, INF);
dist[s] = 0;
for (int i = 0; i < n - 1; ++i)
for (auto& [u, v, w] : edges)
if (dist[u] < INF && dist[u] + w < dist[v])
dist[v] = dist[u] + w;
for (auto& [u, v, w] : edges)
if (dist[u] < INF && dist[u] + w < dist[v]) return false; // negative cycle
return true;
}
\(O(VE)\). Why \(V-1\) passes: the shortest simple path has at most \(V-1\) edges, and each pass guarantees at least one more edge of it is correct.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
n/.style={draw, thick, circle, minimum size=0.62cm, font=\scriptsize\bfseries},
a/.style={->, thick}]
\node[n] (s) at (0,0) {S};
\node[n] (a) at (1.5,0.8) {A};
\node[n] (b) at (1.5,-0.8) {B};
\node[n] (t) at (3.1,0) {T};
\draw[a] (s) -- node[above, font=\scriptsize] {2} (a);
\draw[a] (s) -- node[below, font=\scriptsize] {1} (b);
\draw[a] (b) -- node[below, font=\scriptsize] {1} (t);
\draw[a, red!65, dashed] (a) -- node[right, font=\scriptsize] {-2} (b);
\node[font=\scriptsize, anchor=north] at (1.55,-1.3) {B is settled at 1; A -> B finds 0 too late};
\end{tikzpicture}
\(O(V^2)\)?
ASolution
Each edge can trigger a heap push (\(\log V\) each), so the bound is \(O(E \log V)\) plus \(O(V \log V)\) for extractions. The \(O(V^2)\) version scans for the minimum and is better only on dense graphs.
ASolution
It makes them undefined: walking the cycle repeatedly decreases the cost without bound, so no minimum exists.
Floyd–Warshall
All-pairs shortest paths in \(O(V^3)\) with \(O(V^2)\) memory. The recurrence allows intermediate vertices from a growing set:
\[ d[i][j] = \min\big(d[i][j],\ d[i][k] + d[k][j]\big) \]
void floyd(vector<vector<long long>>& d) { // d initialized with INF, 0 on diagonal
int n = (int)d.size();
for (int k = 0; k < n; ++k) // k must be the OUTER loop
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
if (d[i][k] < INF && d[k][j] < INF)
d[i][j] = min(d[i][j], d[i][k] + d[k][j]);
}
Why \(k\) is outer: after iteration \(k\), d[i][j] is the shortest path using
intermediates from {0..k}. Putting k inside lets a path reuse a vertex it has
not been allowed to use yet, which is wrong. This is the most common Floyd bug.
A negative cycle shows up as a negative value on the diagonal after the run. Use
long long and a large INF (not INT_MAX, because INF + w overflows).
Floyd also computes transitive closure (boolean version), and it is the easiest way to answer many all-pairs queries when \(V \le 500\).
k as the innermost loop?ASolution
The DP invariant is “paths with intermediates in {0..k}”. If k is inner, a
relaxation can use a higher-index intermediate before its own iteration, so the
invariant breaks and paths are missed.
Minimum spanning trees
An MST connects all vertices with minimum total edge weight. Both algorithms are greedy and both are correct because of the cut property: the lightest edge across any cut belongs to some MST.
Kruskal. Sort edges, add one if it joins two different components (DSU).
struct DSU {
vector<int> p, sz;
explicit DSU(int n) : p(n), sz(n, 1) { iota(p.begin(), p.end(), 0); }
int find(int x) { return p[x] == x ? x : p[x] = find(p[x]); }
bool unite(int a, int b) {
a = find(a); b = find(b);
if (a == b) return false;
if (sz[a] < sz[b]) swap(a, b);
p[b] = a; sz[a] += sz[b];
return true;
}
};
long long kruskal(int n, vector<array<int,3>>& edges) { // {w, u, v}
sort(edges.begin(), edges.end());
DSU dsu(n);
long long total = 0;
int used = 0;
for (auto& [w, u, v] : edges) {
if (!dsu.unite(u, v)) continue;
total += w;
if (++used == n - 1) break;
}
return used == n - 1 ? total : -1; // -1: not connected
}
\(O(E \log E)\) for the sort, then near-\(O(E)\) for the unions.
Prim. Grow one tree from a start vertex, always adding the cheapest edge that leaves it. A heap gives \(O((V+E)\log V)\), which is better on dense graphs.
long long prim(int n, const vector<vector<pair<int,int>>>& adj) {
vector<bool> used(n, false);
priority_queue<pair<int,int>, vector<pair<int,int>>, greater<>> pq;
pq.push({0, 0});
long long total = 0;
int taken = 0;
while (!pq.empty() && taken < n) {
auto [w, u] = pq.top(); pq.pop();
if (used[u]) continue;
used[u] = true; total += w; ++taken;
for (auto [v, wt] : adj[u]) if (!used[v]) pq.push({wt, v});
}
return taken == n ? total : -1;
}
| Kruskal | Prim | |
|---|---|---|
| Data structure | DSU | heap |
| Complexity | \(O(E \log E)\) | \(O((V+E)\log V)\) |
| Best for | sparse, edge list | dense, adjacency list |
| Extra | detects disconnected graph | needs a start vertex |
MST is for “connect everything cheapest”, not for “cheapest path between two points”. A shortest-path tree and an MST can be different trees; mixing them up is a common wrong answer.
ASolution
It only adds an edge when its endpoints are in different DSU components. An edge inside one component would close a cycle, so it is skipped.
Disjoint Set Union
DSU maintains a partition under union and answers find (which set). With union
by size and path compression, both are amortized \(O(\alpha(n))\), which is at most
4 for any practical \(n\) — effectively constant.
int find(int x) {
if (p[x] != x) p[x] = find(p[x]); // path compression
return p[x];
}
Union by size keeps trees shallow; path compression flattens them on the way up. Either alone gives \(O(\log n)\); together, the inverse Ackermann bound.
Uses: Kruskal, undirected cycle detection, counting components while adding edges, “accounts merge”, percolation, and offline connectivity queries.
ASolution
Each union attaches the smaller tree under the larger, so a node’s depth increases only when its component at least doubles. That bounds depth by \(\log_2 n\).
Strongly connected components
An SCC is a maximal set where every vertex reaches every other. Condensing each SCC to a single node gives a DAG, which is why SCCs are the standard first step for “circular dependency” and 2-SAT.
Kosaraju uses two DFS passes: order vertices by finishing time on the original graph, then traverse the reversed graph in reverse finishing order. Each tree in the second pass is one SCC.
void dfs1(int u, const vector<vector<int>>& g, vector<bool>& seen,
vector<int>& order) {
seen[u] = true;
for (int v : g[u]) if (!seen[v]) dfs1(v, g, seen, order);
order.push_back(u);
}
void dfs2(int u, const vector<vector<int>>& rg, vector<int>& comp, int c) {
comp[u] = c;
for (int v : rg[u]) if (comp[v] == -1) dfs2(v, rg, comp, c);
}
vector<int> kosaraju(const vector<vector<int>>& g, const vector<vector<int>>& rg) {
int n = (int)g.size();
vector<bool> seen(n, false);
vector<int> order;
for (int i = 0; i < n; ++i) if (!seen[i]) dfs1(i, g, seen, order);
vector<int> comp(n, -1);
int c = 0;
for (int i = n - 1; i >= 0; --i)
if (comp[order[i]] == -1) dfs2(order[i], rg, comp, c++);
return comp;
}
Why it works: the vertex with the largest finishing time in the original graph belongs to a source SCC of the condensation. In the reversed graph, that SCC cannot reach anything outside itself, so the DFS stops exactly at its boundary. Removing it and repeating gives the rest.
Tarjan does it in one pass with a low value: the smallest discovery time
reachable from a subtree, including back edges to vertices still on the stack.
When low[u] == tin[u], u is the root of an SCC and everything above it on the
stack forms that component.
int timer = 0;
vector<int> tin, low, comp;
vector<bool> onStack;
stack<int> st;
void tarjan(int u, const vector<vector<int>>& g) {
tin[u] = low[u] = ++timer;
st.push(u);
onStack[u] = true;
for (int v : g[u]) {
if (tin[v] == 0) {
tarjan(v, g);
low[u] = min(low[u], low[v]);
} else if (onStack[v]) {
low[u] = min(low[u], tin[v]);
}
}
if (low[u] == tin[u]) {
while (true) {
int w = st.top(); st.pop();
onStack[w] = false;
comp[w] = u; // representative of the SCC
if (w == u) break;
}
}
}
Both are \(O(V+E)\): each vertex enters and leaves the stack once, and each edge is examined once per endpoint. The recursion depth is an issue on long chains; the iterative Tarjan exists and is worth knowing if \(V\) is \(10^6\).
\begin{tikzpicture}[font=\rmfamily, >=stealth,
n/.style={draw, thick, circle, minimum size=0.62cm, font=\scriptsize\bfseries},
a/.style={->, thick}]
\node[n, fill=orange!25] (a) at (0,0) {A};
\node[n, fill=orange!25] (b) at (1.1,0.5) {B};
\node[n, fill=orange!25] (c) at (1.1,-0.5) {C};
\node[n, fill=blue!18] (d) at (3.0,0) {D};
\draw[a] (a) -- (b); \draw[a] (b) -- (c); \draw[a] (c) -- (a);
\draw[a] (b) -- (d);
\draw[a, dashed, red!55] (d) to[bend left=30] (b);
\node[font=\scriptsize, anchor=west] at (3.7,0) {SCC (ABC) -> D};
\end{tikzpicture}
ASolution
The reversed graph breaks the one-way edges between SCCs, so a DFS from a finishing-order root cannot leak into other components. The second pass then collects exactly one SCC per tree.
tin[v] rather than low[v]?ASolution
A back edge points to an ancestor on the stack; the walk up must stop there.
Using low[v] could pull in a value from a different, already-finished
component and merge SCCs incorrectly.
Bridges and articulation points
A bridge is an edge whose removal disconnects the graph. An articulation
point is a vertex whose removal does. Both come from one DFS with tin and
low.
void dfs(int u, int parent, const vector<vector<int>>& adj,
vector<int>& tin, vector<int>& low, int& timer,
vector<pair<int,int>>& bridges) {
tin[u] = low[u] = timer++;
for (int v : adj[u]) {
if (v == parent) continue;
if (tin[v] != -1) {
low[u] = min(low[u], tin[v]); // back edge
} else {
dfs(v, u, adj, tin, low, timer, bridges);
low[u] = min(low[u], low[v]);
if (low[v] > tin[u]) bridges.push_back({u, v});
}
}
}
low[v] > tin[u] means the subtree of v has no back edge to u or above, so
the edge u–v is the only way in or out. For articulation points the condition
is low[v] >= tin[u], plus a special case for the root (it is an articulation
point only if it has more than one DFS child).
Parallel edges break the v == parent check: skipping by parent removes both
copies. Track edge ids instead, and skip only the id you arrived on.
>= while the bridgecondition is >?
ASolution
If low[v] == tin[u], v’s subtree can still reach u itself, so removing the
edge u–v is fine but removing the vertex u disconnects it. A bridge needs
strictly no way back.
Bipartite graphs
A graph is bipartite if its vertices split into two sets with every edge crossing between them. Equivalently: it contains no odd cycle. Test with BFS 2-colouring.
bool isBipartite(const vector<vector<int>>& adj) {
int n = (int)adj.size();
vector<int> color(n, -1);
for (int s = 0; s < n; ++s) {
if (color[s] != -1) continue;
queue<int> q; q.push(s); color[s] = 0;
while (!q.empty()) {
int u = q.front(); q.pop();
for (int v : adj[u]) {
if (color[v] == -1) { color[v] = color[u] ^ 1; q.push(v); }
else if (color[v] == color[u]) return false;
}
}
}
return true;
}
Disconnected graphs need the outer loop; a single BFS only covers one component. Bipartite matching (Hungarian, Hopcroft–Karp) builds on this, as does 2-SAT’s implication graph consistency.
ASolution
An odd cycle cannot alternate between two colours and close. Conversely, BFS layers give a valid 2-colouring when every cycle is even.
Bugs and edge cases
- 1-indexed input. Subtract 1 from every vertex id, once, at read time.
- Self-loops and parallel edges. Break cycle detection, bridges, and DSU assumptions. Decide whether to ignore them.
- Disconnected input. Every traversal needs the outer loop over all vertices;
Dijkstra with unreachable targets returns
INF, not 0. INF + woverflow. UseLLONG_MAX/4and guarddist[u] < INF.- Recursion depth. DFS on a \(10^5\) chain overflows. Have an iterative version ready.
- Dijkstra with negative weights. Silently wrong, not an error. Check the problem’s weight constraints.
- Floyd loop order.
koutermost, always. - Kahn’s queue. Initial in-degrees from all edges, including duplicates; a multigraph needs them counted.
- MST versus shortest path. An MST minimizes total wiring, not the distance between two nodes.
path. What is the first thing to check?
ASolution
Negative edge weights. Dijkstra’s settled-distance invariant does not hold with negatives, and it can finalize a vertex before its true distance is known.
Next: Dynamic Programming (DSA Core #7) — the state, the transition, the base case, and the order.