1
Dijkstra's Shortest Path
Algorithm
Finds the shortest distance from one source to every node in a graph with non-negative weights. Greedy: always expand the closest unvisited node, using a min-heap. Complexity O((V + E) log V).
For negative weights use Bellman-Ford O(VE); for all pairs use Floyd-Warshall O(V³).
vector<int> dijkstra(int src, vector<vector<pair<int,int>>> &adj) { // adj[u] = {v, w}
vector<int> dist(adj.size(), INT_MAX);
priority_queue<pair<int,int>, vector<pair<int,int>>, greater<>> pq; // {dist, node}
dist[src] = 0;
pq.push({0, src});
while (!pq.empty()) {
auto [d, u] = pq.top(); pq.pop();
if (d > dist[u]) continue; // outdated entry
for (auto [v, w] : adj[u]) {
if (dist[u] + w < dist[v]) { // relax the edge
dist[v] = dist[u] + w;
pq.push({dist[v], v});
}
}
}
return dist;
}