460. Dijkstra

Step 1: Initialize

Example

Graph nodes: A, B, C, D

Start node: A

Distances:

Step 2: Select the Unvisited Node with the Smallest Distance

Among all unvisited nodes, pick the one with the smallest known distance. Let’s call this the current node.

Step 3: Update Neighboring Distances

For each neighbor of the current node:

  1. Calculate the tentative distance:

    distance(current) + weight(current → neighbor)

  2. If this tentative distance is less than the known distance, update it.

Example

If has weight 4 and distance to A is 0:

Tentative distance to B = 0 + 4 = 4

If current distance to B is ∞, update to 4

Step 4: Mark the Current Node as Visited

Step 5: Repeat Until All Nodes Are Visited

Step 6: Reconstruct the Shortest Paths (Optional)

Example