DSA · Pro · Pattern 2 of 9
Shortest Paths & Topological Sort
15 problems.
Your progress0%
- 1st Visit
- 0/15
- 2nd Visit
- 0/15
- Revise
- 0/15
About this pattern
Weighted graphs need more than plain BFS. Dijkstra's algorithm finds single-source shortest paths when every weight is non-negative, using a min-heap in O((V + E) log V). Bellman-Ford handles negative weights or a cap on the number of edges in O(V * E), and Floyd-Warshall gives all-pairs distances in O(V^3) for small graphs. Topological sort orders a directed acyclic graph so that every edge points forward; it detects cycles and lets a DP run over dependencies such as prerequisites or task durations. Signals: weighted edges, a minimum total cost or time, precedence constraints, or an order of letters or tasks to reconstruct.
// Dijkstra from src; adj[u] holds {v, w} with w >= 0
vector<long long> dijkstra(int src, const vector<vector<pair<int, int>>>& adj) {
vector<long long> dist(adj.size(), LLONG_MAX);
priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<>> pq;
dist[src] = 0;
pq.push({0, src});
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;
}