Dijkstra’s algorithm is a shortest-path algorithm for graphs. It finds the shortest path from a source vertex to all other vertices in a weighted graph. Here is an overview of the algorithm and its basic syntax.
visited
and a set of tentative distances dist
to all vertices to infinity, except for the source vertex, which has distance 0.current
.v
of current
that is still unvisited:
v
via current
: dist[current] + weight(current, v)
.dist[v]
, update dist[v]
to the new, lower value.current
as visited.dist
.import heapq
def dijkstra(graph, source):
visited = set()
dist = {v: float('inf') for v in graph}
dist[source] = 0
heap = [(0, source)]
while heap:
(d, current) = heapq.heappop(heap)
if current in visited:
continue
visited.add(current)
for v, w in graph[current].items():
if v in visited:
continue
if dist[current] + w < dist[v]:
dist[v] = dist[current] + w
heapq.heappush(heap, (dist[v], v))
return dist
#include <queue>
#include <unordered_map>
#include <vector>
using namespace std;
typedef unordered_map<int, unordered_map<int, int>> Graph;
vector<int> dijkstra(const Graph& graph, int source) {
vector<int> dist(graph.size(), INT_MAX);
dist[source] = 0;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
pq.push({0, source});
while (!pq.empty()) {
int current = pq.top().second;
pq.pop();
for (auto neighbor : graph.at(current)) {
int v = neighbor.first;
int w = neighbor.second;
if (dist[current] + w < dist[v]) {
dist[v] = dist[current] + w;
pq.push({dist[v], v});
}
}
}
return dist;
}