In Part 1 we covered what graphs are and how to represent them. In Part 2 we explored BFS and DFS — the two ways to traverse a graph. Now it’s time for the advanced algorithms that solve real engineering problems: finding the shortest weighted path, connecting a network at minimum cost, and efficiently grouping nodes.
This is Part 3 of a 3-part series. Start from Part 1 if you’re new to graphs.
Dijkstra’s Algorithm — Shortest Path in a Weighted Graph
The Problem
BFS finds the shortest path in an unweighted graph (fewest edges). But what if edges have costs — distances, latency, price? BFS treats a 1km road the same as a 1000km road. We need something smarter.
Dijkstra’s algorithm computes the shortest distance from one source vertex to every other vertex in a weighted graph. It’s the algorithm inside your GPS.
Important constraint: Dijkstra only works correctly with non-negative edge weights. If your graph has negative weights, use Bellman-Ford instead.
The Core Idea: Greedy Relaxation
Dijkstra always processes the vertex with the smallest known distance next. When it processes a vertex, it checks whether going through that vertex offers a shorter route to any of its neighbors. Updating a neighbor’s distance is called relaxation.
Think of it like this: you’re planning a road trip and you always pick the nearest unvisited city next. From there, you check if you can reach other cities more cheaply by routing through it.
Step-by-Step Example

Graph (directed, weighted):
A → B : 5
A → C : 1
A → D : 4
A → E : 10
C → D : 2
D → E : 5
B → E : 6
Starting from A, with all distances initialized to ∞:
Initial: dist = {A:0, B:∞, C:∞, D:∞, E:∞}
Heap: [(0, A)]
Given this is min-heap, it always processes the node with the minimum distance value
Process A (dist 0):
Relax A→B: dist[B] = 0+5 = 5 ✓
Relax A→C: dist[C] = 0+1 = 1 ✓
Relax A→D: dist[D] = 0+4 = 4 ✓
Relax A→E: dist[E] = 0+10 = 10 ✓
Pop A
Heap: [(1,C), (4,D), (5,B), (10,E)]
Process C (dist 1):
Relax C→D: dist[D] = min(4, 1+2) = 3 ← update!
Pop C
Heap: [(3,D), (4,D-old), (5,B), (10,E)]
Process D (dist 3):
Relax D→E: dist[E] = min(10, 3+5) = 8 ← update!
Pop D (dist 3)
Heap: [(4,D-old-skip), (5,B), (8,E)]
Process D (dist 4, D-old-skip):
Nothing to update
Process B (dist 5):
Relax B→E: dist[E] = min(8, 5+6) = 8 ← no change
Process E (dist 8): Done ✓
Result: A→B=5, A→C=1, A→D=3 (via C), A→E=8 (via C→D)
Dijkstra’s in C++
cpp
void dijkstra(unordered_map<int, vector<pair<int,int>>> &graph,
vector<int> &dist) {
// Min-heap stores (current_dist, node)
priority_queue<pair<int,int>,
vector<pair<int,int>>,
greater<pair<int,int>>> pq;
pq.push({0, source});
while (!pq.empty()) {
auto [currDist, u] = pq.top();
pq.pop();
// Stale entry in heap — skip
if (currDist > dist[u]) continue;
for (auto &[v, weight] : graph[u]) {
if (dist[u] + weight < dist[v]) {
dist[v] = dist[u] + weight;
pq.push({dist[v], v}); // relax
}
}
}
}
// Setup in main():
vector<int> dist(n, INT_MAX);
dist[source] = 0;
dijkstra(graph, dist);
Time complexity: O((V + E) log V) with a binary min-heap Key data structure: Priority queue (min-heap)
Minimum Spanning Tree (MST)
The Problem
You’re building a network — fiber cables between offices, or roads between cities. You need to connect all nodes while minimizing total cost. But you don’t want redundant connections (cycles waste money).
This is exactly the Minimum Spanning Tree problem.
A spanning tree of an undirected connected graph:
- Includes every vertex
- Has exactly V−1 edges
- Contains no cycles
The MST is the spanning tree with the smallest possible total edge weight.
Quick Example
Graph: (A) --1-- (B)
| \ |
4 5 3
| \ |
(C) --2-- (D)
All possible spanning trees use 3 edges (4 nodes − 1). The MST picks:
- A–B (weight 1)
- C–D (weight 2)
- B–D (weight 3)
- Total: 6 — cheaper than any other combination
Edges A–C (4) and A–D (5) are excluded because cheaper alternatives connect those components.
Two Algorithms to Find the MST
There are two classic algorithms, each with a different strategy:
Kruskal’s Algorithm — Edge-Centric
Strategy: Sort all edges by weight. Add them one by one, skipping any that would create a cycle. Stop when you have V−1 edges.
How it detects cycles: Union-Find (we’ll cover this next).
cpp
void kruskal(UnionFind &uf, vector<Edge> &edges, vector<Edge> &mst) {
// Sort edges by weight (ascending)
sort(edges.begin(), edges.end(),
[](const Edge &a, const Edge &b) {
return a.weight < b.weight;
});
for (auto &e : edges) {
// Only add if the two endpoints are in different components
if (uf.find(e.src) != uf.find(e.dst)) {
uf.merge(e.src, e.dst);
mst.push_back(e);
}
if (mst.size() == numNodes - 1) break; // MST complete
}
}
Time complexity: O(E log E) — dominated by sorting
Prim’s Algorithm — Vertex-Centric
Strategy: Start from any vertex. Greedily add the cheapest edge that connects a vertex already in the MST to one outside it. Repeat until all vertices are included.
It works similarly to Dijkstra’s — a min-heap tracks the cheapest way to add each unvisited vertex.
cpp
void prim(unordered_map<int, vector<pair<int,int>>> &g) {
vector<bool> inMST(numNodes + 1, false);
vector<int> dist(numNodes + 1, INT_MAX);
priority_queue<pair<int,int>,
vector<pair<int,int>>,
greater<pair<int,int>>> pq;
dist[0] = 0;
pq.push({0, 0});
int mstCost = 0;
while (!pq.empty()) {
auto [currDist, node] = pq.top();
pq.pop();
if (inMST[node]) continue;
inMST[node] = true;
mstCost += currDist;
for (auto &[neighbor, weight] : g[node]) {
if (!inMST[neighbor] && weight < dist[neighbor]) {
dist[neighbor] = weight;
pq.push({dist[neighbor], neighbor});
}
}
}
}
Time complexity: O(E log V)
Kruskal’s vs. Prim’s
| Kruskal’s | Prim’s | |
|---|---|---|
| Approach | Edge-centric | Vertex-centric |
| Data structure | Union-Find | Min-heap |
| Best for | Sparse graphs | Dense graphs |
| Complexity | O(E log E) | O(E log V) |
Both produce a valid MST — the choice is about which fits your graph’s structure better.
Union Find — The Power Tool Behind Kruskal’s
The Problem
When building the MST with Kruskal’s, we need to answer one question repeatedly and fast: do these two nodes already belong to the same connected component? If yes, adding the edge between them would create a cycle — skip it.
Union Find (also called Disjoint Set Union, or DSU) is a data structure designed exactly for this.
Three Operations
- Make-Set(x): Initialize x as its own group (it’s its own root)
- Find(x): Return the root/representative of x’s group
- Union(x, y): Merge the groups containing x and y
Two Key Optimizations
Without optimizations, Find can be O(n) in the worst case (a long chain). Two techniques fix this:
1. Union by Size: When merging two trees, always attach the smaller tree under the larger one. This keeps the tree height at O(log n).
2. Path Compression: When calling Find(x), make every node on the path point directly to the root. Future finds on those nodes become nearly instant.
Together, these bring Find and Union to amortized nearly O(1) — effectively constant time for all practical purposes.
Union Find in C++
cpp
class UnionFind {
vector<int> parents, sizes;
public:
UnionFind(int n) : parents(n), sizes(n, 1) {
// Each node starts as its own parent
iota(parents.begin(), parents.end(), 0);
}
int find(int node) {
if (parents[node] == node) return node;
// Path compression: point directly to root
return parents[node] = find(parents[node]);
}
void merge(int a, int b) {
a = find(a);
b = find(b);
if (a == b) return; // Already same component
// Union by size: smaller tree goes under larger
if (sizes[a] < sizes[b]) swap(a, b);
parents[b] = a;
sizes[a] += sizes[b];
}
bool connected(int a, int b) {
return find(a) == find(b);
}
};
Where Union Find Shows Up
- Kruskal’s MST — detect cycles as edges are added
- Connected components — group nodes dynamically as edges arrive
- Network connectivity — check if two servers can communicate in real time
- Social grouping — merge friend groups, detect clusters
- Pixel clustering — image segmentation by connecting similar pixels
Putting It All Together
Here’s a quick decision guide for picking the right algorithm:
| Problem | Algorithm | Why |
|---|---|---|
| Shortest path, unweighted | BFS | Simplest, O(V+E) |
| Shortest path, weighted (non-negative) | Dijkstra | Greedy + min-heap |
| Shortest path, negative weights | Bellman-Ford | Handles negatives |
| Minimum cost to connect all nodes | Kruskal or Prim | MST algorithms |
| Are two nodes in the same component? | Union Find | Near O(1) per query |
| Valid ordering of dependencies | Topological Sort (DFS) | Works on DAGs |
Series Wrap-Up
Over these three posts, you’ve gone from zero to covering the most important graph algorithms used in real software systems:
- Part 1 — Graphs, terminology, adjacency list vs. matrix
- Part 2 — BFS (shortest unweighted path), DFS (exploration + cycle detection), Topological Sort
- Part 3 — Dijkstra (weighted shortest path), MST with Kruskal & Prim, Union Find
The best way to solidify this knowledge is to practice. Try these problems on LeetCode or Codeforces:
- BFS/DFS: Number of Islands (LC 200), Clone Graph (LC 133)
- Topological Sort: Course Schedule (LC 207), Course Schedule II (LC 210)
- Dijkstra: Network Delay Time (LC 743), Path with Minimum Effort (LC 1631)
- Union Find: Number of Connected Components (LC 323), Accounts Merge (LC 721)
Good luck, and happy graph traversing!