Chapter 14 · Simulation

Dijkstra's Algorithm Simulator

← Chapter 14

Example weighted graph loaded. Drag the vertices or run Dijkstra.

Vertices0
Edges0
Settled0
Relaxations0

Current step

—

Selected shortest path

—

Min-priority queue

Distance / predecessor table

VertexDistancePrevState

Dijkstra's Algorithm Simulator

Dijkstra's algorithm finds shortest paths from a single source vertex in a graph whose edge weights are nonnegative. This simulator uses an undirected weighted graph, tentative distances, predecessors, and a min-priority queue.

How to use it

  • Add or remove vertices (Remove Vertex deletes the vertex selected as Endpoint 1); pick two endpoints and a weight (0–99), then use Add / Update or Remove Edge. Drag vertices to tidy up the drawing.
  • Pick a source and press Run: every settled vertex and every relaxation is shown step by step, and the priority queue and the distance / predecessor table update after each step.
  • To highlight the shortest path found by the last run, pick a target and press Path to Target.
  • Load Example loads the sample graph and Random a random one; Clear empties the graph and Cancel stops a running animation.

Dijkstra ideas

  • Greedy settling: among the vertices not yet settled, the one with the smallest tentative distance is settled next. Because no weight is negative, that distance can no longer improve.
  • Relaxation: for an edge (u, v) of weight w, if dist[u] + w < dist[v], set dist[v] = dist[u] + w and prev[v] = u.
  • Path reconstruction: follow the predecessor links backward from the target to rebuild the shortest path.
  • Unreachable vertices: a vertex outside the source's component keeps distance ∞, and there is no path to it.

When Dijkstra applies

ConditionOutcome
All edge weights nonnegativeDijkstra gives correct results.
Some edge has negative weightUse Bellman–Ford or another suitable algorithm.
All weights equalBFS is enough.
Shortest paths needed for all pairsRun it once from each source, or use an all-pairs algorithm.

With a binary heap the running time is O((n + m) log n), for n vertices and m edges.