Skip to content
Graph Intelligence Hub
Menu

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

TimeO((V + E) log V) with a binary heap
SpaceO(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, nodeIds

Procedure 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 complexityO((V + E) log V) with a binary heap
Space complexityO(V)

Relationships

Prerequisite of
Prerequisites
Implemented by
Related