Algorithm
Dijkstra's shortest path
activeNeeds verification
Computes shortest paths from a source in graphs with non-negative edge weights by repeatedly settling the closest unsettled node.
Definition
Intuition
Expand a frontier outward in order of distance; once the nearest frontier node is taken from the priority queue, its distance can never improve.
Pseudocode
Dijkstra(G, w, s):
dist[v] = ∞ for all v; dist[s] = 0
PQ = {(0, s)}
while PQ not empty:
(d, u) = PQ.pop_min()
if d > dist[u]: continue
for (v, w_uv) in out_edges(u):
if dist[u] + w_uv < dist[v]:
dist[v] = dist[u] + w_uv; prev[v] = u; PQ.push((dist[v], v))
Complexity
| Time | O((V + E) log V) with a binary heap |
|---|---|
| Space | O(V) |
Python
import networkx as nx
path = nx.dijkstra_path(G, 'A', 'F', weight='weight')
length = nx.dijkstra_path_length(G, 'A', 'F', weight='weight')Cypher (Neo4j GDS)
MATCH (s:Place {name: 'A'}), (t:Place {name: 'F'})
CALL gds.shortestPath.dijkstra.stream('roads', {
sourceNode: s, targetNode: t, relationshipWeightProperty: 'cost'})
YIELD totalCost, nodeIds RETURN totalCost, nodeIdsProcedure names and options vary between GDS versions; check the GDS docs for your version.
An interactive step-by-step visualizer for this algorithm is planned for phase 3.
Profile
| Time complexity | O((V + E) log V) with a binary heap |
|---|---|
| Space complexity | O(V) |
Relationships
- Belongs to
- Introduced by
- Prerequisite of
- Prerequisites
- Breadth-first search (BFS)(Algorithm)
- Implemented by
- Neo4j Graph Data Science(Library / framework)
- NetworkX(Library / framework)
- Related
- Dijkstra's shortest-path algorithm(Timeline event)