Skip to content

Weighted Graphs & Dijkstra

When edges have costs, the shortest route is no longer the one with the fewest edges

1. Edges with costs

A weighted graph attaches a number to every edge: distance, time, price, or risk. The cost of a path is the sum of its edge weights. The shortest path is the one with the smallest total cost, not necessarily the fewest hops. A direct edge can be more expensive than a two-edge detour.

Path cost

The same graph can be directed or undirected. Dijkstra works on both, as long as every edge weight is non-negative. Negative weights need Bellman–Ford or a different model.

2. Relaxation

Keep a tentative distance for every vertex. Initially the source is 0 and everything else is infinity. Relaxing an edge (u, v) asks a simple question: is the path through u cheaper than the best known path to v? If yes, update the distance and remember the parent.

Relaxation
if dist[u] + weight(u, v) < dist[v]:
  dist[v] = dist[u] + weight(u, v)
  parent[v] = u

The parent array is what lets you reconstruct the route at the end. Without it, you know the cost but not the path.

3. Dijkstra

Dijkstra repeatedly settles the unsettled vertex with the smallest tentative distance, then relaxes its outgoing edges. A binary min-heap makes the “smallest tentative distance” operation efficient. The settled set grows once per vertex; each edge is relaxed once.

Dijkstra skeleton
dist[source] = 0
pq = [(0, source)]
while pq not empty:
  d, u = pq.extract_min()
  if d > dist[u]: continue
  for v, w in adjacency[u]:
    if dist[u] + w < dist[v]:
      dist[v] = dist[u] + w
      parent[v] = u
      pq.insert((dist[v], v))
With a binary heap

This is the same priority queue from the heap lesson. The heap is not a detail; it is what turns the repeated “find the minimum” step from O(V) into O(log V).

Example: A→B 4, A→C 1, C→B 2, B→D 1, C→D 5

Start at A: dist A = 0, B = ∞, C = ∞, D = ∞. Relax A→B to 4 and A→C to 1. Settle C (1), then relax C→B to 3 and C→D to 6. Settle B (3), then relax B→D to 4. Settle D at 4.

The shortest route is A→C→B→D = 4. The direct-looking A→B→D is 5, and A→C→D is 6.

4. Why non-negative

Dijkstra settles a vertex when it is the closest unsettled one. That argument assumes no later path can be cheaper. A negative edge breaks it: a vertex settled now could be improved later by a path that goes through a negative edge.

  • Dijkstra — one source, non-negative weights, O((V+E) log V).
  • Bellman–Ford — one source, negative edges allowed, O(VE).
  • Floyd–Warshall — all pairs, O(V³).
  • BFS — unweighted graphs, O(V+E).

5. Practice

Try it

Why does the cheapest path sometimes use more edges than a direct edge?

Try it

What does the priority queue store in Dijkstra?

Try it

Why does a negative edge break Dijkstra?

Try it

How do you reconstruct the shortest path after running Dijkstra?

6. Resources

The Dijkstra playground uses a weighted grid: each cell has a terrain cost, and the path cost is the sum of the cells you enter. Draw a wall and watch the route change.

Open the Dijkstra playground →

Continue the track

Open the playground for this topic

Dijkstra Playground →

Run Dijkstra on weighted terrain, draw walls, and compare the settled distances with the cheapest path.

Site soundtrack