Dijkstra’s Algorithm is an algorithm that computes the length of the shortest path from a vertex to every vertex in a graph with non-negative edge weights in
- time and space, or
- time and space.
Hint
This problem can also be solved by the Floyd-Warshall Algorithm in time and space.
Algorithm 0
Lemma
Let denote the length of the shortest path from to that only passes through vertices in .
Proof
Let be a vertex in , be the first vertex on a shortest path from to such that . Then
Therefore,
Maintaining a set of unvisited vertices, repeatedly visiting a vertex in and applying the lemma to find until yield an algorithm that solves the problem in time and space.
std::vector dist(n, inf);
dist[0] = 0;
std::vector<int> s(n);
std::iota(s.begin(), s.end(), 0);
while (!s.empty()) {
int u = std::ranges::min(s, [&](int i, int j) -> bool {
return dist[i] < dist[j];
});
std::erase(s, u);
for (auto [v, w] : adj[u]) {
dist[v] = std::min(dist[v], dist[u] + w);
}
}
return dist;Algorithm 1
Based on Algorithm 0, using a binary heap to maintain the set yields an algorithm that solves the problem in time and space.
std::vector dist(n, inf);
dist[0] = 0;
std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>>, std::greater<>> s;
s.emplace(dist[0], 0);
while (!s.empty()) {
auto [prio, u] = s.top();
s.pop();
if (prio != dist[u]) {
continue;
}
for (auto [v, w] : adj[u]) {
if (dist[v] > dist[u] + w) {
dist[v] = dist[u] + w;
s.emplace(dist[v], v);
}
}
}
return dist;