From edge counts to path costs
A shortest-path problem asks for a route, not merely a way to connect the
graph. Fix a source vertex s. For every reachable vertex v, the goal is to
minimize the sum of the edge weights along an s-to-v path. This is the
single-source shortest-path problem.
With equal edge costs, BFS
finds shortest paths by processing successive edge-count layers. Unequal weights
break that correspondence: a direct edge of weight 9 may be more expensive
than a two-edge route of weights 3 and 2. Dijkstra's algorithm therefore
keeps tentative costs, improves them by relaxation, and finalizes vertices
in nondecreasing order of their current estimates.
Applicability condition — nonnegative weights only. Dijkstra's greedy finalization is correct only when every edge has weight at least zero. A zero-weight edge is allowed; a negative edge is not. A graph containing a negative edge requires a different shortest-path method.
Tentative paths and relaxation
Let be a directed or undirected graph, let
be the weight of edge (u,v), and fix a source s. The weight of
a path is the sum of its edge weights. Write for the minimum path
weight from s to v, and write when v is unreachable.
Definition 5.3.1
(Tentative distance and predecessor)
d[v] is the smallest cost of an s-to-v path discovered so far. It is an
upper bound on the true shortest distance . The value pred[v]
records the vertex immediately before v on the path that currently realizes
d[v].
Initially,
and every predecessor is undefined. Whenever a better path is found, the distance and predecessor must be changed together.
Definition 5.3.2
(Relaxation)
To relax an edge (u,v) of weight w(u,v), compare the old estimate d[v]
with the candidate obtained by extending the current path to u:
If the candidate is strictly smaller, set
Otherwise leave both fields unchanged.
The settled set S contains vertices whose shortest distances have been
proved final. In each round, Dijkstra selects an unsettled vertex with minimum
tentative distance, adds it to S, and relaxes its outgoing edges. A tie may be
broken arbitrarily; it can change the predecessor tree but not the final
distances.
Dijkstra(G, s):
for each vertex v:
d[v] = infinity
pred[v] = undefined
d[s] = 0
S = empty set
while an unsettled vertex has finite distance:
u = unsettled vertex with minimum d[u]
add u to S
for each outgoing edge (u, v) with v not in S:
candidate = d[u] + w(u, v)
if candidate is smaller than d[v]:
d[v] = candidate
pred[v] = u
When the loop ends, a reachable target's path is reconstructed backwards:
start at the target, follow pred until s, then reverse the sequence. A
vertex left at infinity has no predecessor path from s.
What a settled distance guarantees
Theorem 5.3.3
(Finite estimates are path costs and upper bounds)
At every point in Dijkstra's algorithm, each finite d[v] is the cost of an
actual discovered path from s to v. Consequently,
Relaxation can only decrease an estimate, and it preserves this upper-bound property.
Theorem 5.3.4
(Safe greedy finalization)
Suppose all edge weights are nonnegative. When Dijkstra selects an unsettled
vertex u having minimum tentative distance, its estimate is exact:
Thus u may be settled permanently.
Theorem 5.3.5
(Predecessors encode shortest paths)
After Dijkstra terminates, following predecessor links from any reachable
vertex v back to s gives a path of cost d[v]. Since settled estimates are
exact, that path is a shortest path. If several shortest paths tie, the stored
predecessor records one of them.
Why the smallest estimate is final
The upper-bound claim follows by induction. The initialization d[s]=0
represents the empty path. Every later finite estimate is created by taking a
path already represented by d[u] and appending edge (u,v). No estimate can
therefore describe a cost smaller than the best possible path.
The first selected vertex is s, whose distance 0 is exact because all
weights are nonnegative. For a later greedy step, assume the settled vertices
already have exact distances, and let u be the unsettled vertex with minimum
d. Consider a shortest path from s to u. Let y be the first unsettled vertex on that path and x its
settled predecessor. When x was settled, (x,y) was relaxed, so d[y] became
at most the cost of the shortest-path prefix ending at y. Combined with the
upper-bound property, this gives
Every edge on the remaining suffix from y to u has nonnegative weight.
Therefore . Minimum selection and the upper-bound
property now squeeze d[u] from both sides:
All quantities are equal, so . The step can fail when a later edge is negative; that is exactly why the nonnegative-weight condition is indispensable.
Stopping when only one target is needed
Suppose the question asks for one shortest path from s to a fixed target t, rather than distances to every vertex. The full algorithm can stop as soon as t is settled: select it as the minimum-distance unsettled vertex and only then return d[t] and its predecessor path. There is no need to relax edges leaving t for this particular answer. When t=s, the first selected vertex already gives the empty path of cost zero.
Counterexample mode
Finding the target is not enough
Consider a directed graph with edges s->t(10), s->a(1), and a->t(1). After processing s, the target has been discovered with d[t]=10, but a has the smaller estimate 1. Settling a and relaxing a->t changes the target's estimate to 2 and its predecessor to a. Stopping when t is first inserted would return 10; waiting until t is selected returns the path s->a->t of cost 2.
Proof X-ray
What early settlement proves
At the moment t is selected, the safe-finalization theorem applies to t exactly as it applies to any other selected vertex: nonnegative edge weights imply d[t]=δ(s,t). Every strict improvement previously recorded a predecessor, so its chain gives one path with that cost. The argument makes no claim that other unsettled estimates are final. If no finite unsettled vertex remains before t is selected, t is unreachable; return that fact rather than a path. In a heap that retains old entries, discard stale entries before applying the target stopping rule.
Equal estimates do not invalidate the target distance, even with zero-weight edges. They do matter if the task asks for all shortest paths. For example, with s->t(5), s->a(5), and a->t(0), either t or a may be selected first. If t is selected first, early stopping gives the correct distance 5 and the direct path, but it has not examined the equally short route through a. The algorithm above stores one predecessor and updates only on strict improvement; it is not an algorithm for enumerating all shortest paths. In particular, zero-weight cycles require care even in defining or enumerating shortest walks.
Relaxation, failure, and modelling examples
Worked example 5.3.6
(One relaxation changes both fields)
Suppose d[u]=7, edge (u,v) has weight 4, and the current record is
d[v]=14 with pred[v]=x. The route through u costs
Relaxation sets d[v]=11 and pred[v]=u. If the old estimate had been 10,
neither field would change. Updating only the number but not the predecessor
would make later path reconstruction inconsistent with the recorded cost.
Worked example 5.3.7
(Complete shortest-path trace from v0)
Use the directed weighted graph with edges
v0->v1(3), v0->v2(2), v0->v3(6), v0->v4(4),
v1->v3(5), v1->v5(5), v2->v4(1), v4->v3(2),
v4->v5(4), and v3->v5(1).
In each distance cell below, the item in parentheses is the predecessor. A dash
means undefined. After settling v2, both v1 and v4 have estimate 3; the
trace breaks this tie by settling v1 first.
| Stage | Chosen vertex | Settled set after the choice | d[v0] | d[v1] | d[v2] | d[v3] | d[v4] | d[v5] |
|---|---|---|---|---|---|---|---|---|
| Initial | — | {} | 0 (—) | infinity (—) | infinity (—) | infinity (—) | infinity (—) | infinity (—) |
Relax from v0 | v0 | {v0} | 0 (—) | 3 (v0) | 2 (v0) | 6 (v0) | 4 (v0) | infinity (—) |
Relax from v2 | v2 | {v0,v2} | 0 (—) | 3 (v0) | 2 (v0) | 6 (v0) | 3 (v2) | infinity (—) |
Relax from v1 | v1 | {v0,v2,v1} | 0 (—) | 3 (v0) | 2 (v0) | 6 (v0) | 3 (v2) | 8 (v1) |
Relax from v4 | v4 | {v0,v2,v1,v4} | 0 (—) | 3 (v0) | 2 (v0) | 5 (v4) | 3 (v2) | 7 (v4) |
Relax from v3 | v3 | {v0,v2,v1,v4,v3} | 0 (—) | 3 (v0) | 2 (v0) | 5 (v4) | 3 (v2) | 6 (v3) |
Finish at v5 | v5 | {v0,v2,v1,v4,v3,v5} | 0 (—) | 3 (v0) | 2 (v0) | 5 (v4) | 3 (v2) | 6 (v3) |
The final distances are 0,3,2,5,3,6. For example, the predecessor chain
reverses to the shortest path
v0 -> v2 -> v4 -> v3 -> v5, whose cost is 2+1+2+1=6.
Notice that v5 improved three times: infinity to 8, then 7, then 6.
Discovery did not mean finalization.
Worked example 5.3.8
(A minimal negative-edge failure)
Consider the directed graph
s->u(1), s->v(2), and v->u(-2).
After relaxing edges out of s, Dijkstra has d[u]=1 and d[v]=2, so it
settles u first. Yet the path s->v->u has cost 2+(-2)=0. When v is
processed later, the algorithm would need to improve a vertex that it already
declared final. The graph has no negative cycle; one negative edge alone is
enough to invalidate greedy finalization.
Worked example 5.3.9
(Weighted grid with an explicit node-to-edge convention)
Find a minimum-cost route from the top-left cell to the bottom-right cell of
this 3 by 4 node-weight grid, where N is blocked:
| Column 1 | Column 2 | Column 3 | Column 4 | |
|---|---|---|---|---|
| Row 1 | 1 | 2 | 5 | 1 |
| Row 2 | 4 | 1 | N | N |
| Row 3 | 1 | 2 | 1 | 1 |
Create one vertex for each unblocked cell. Only a move one cell right or one cell down is allowed; omit an edge whose destination is outside the grid or blocked. Because the data put costs on nodes while Dijkstra expects costs on edges, choose and state this conversion:
Thus an edge charges the cost of entering its destination, while initialization charges the starting cell once. The shortest route to the bottom-right cell is
with total node cost
The competing route down the first column reaches (3,2) with cost 8, whereas
the chosen route reaches it with cost 6; continuing along the common suffix
would give totals 10 and 8. The top-row branch through (1,3) cannot descend
because (2,3) and (2,4) are blocked. If instead one initialized the source
to zero, the chosen edge sum would be 7; adding the source weight recovers the
same reported node-path cost 8. Mixing those two conventions without saying
so creates an off-by-one-cell error.
For an adjacency matrix and a linear scan for the next minimum, Dijkstra takes
time. With adjacency lists and a min-priority queue implemented by a
binary heap with one entry per unsettled vertex and decrease-key updates,
there are at most V extract-min operations and at most E successful
priority updates, giving
time and graph-and-table space. In the right/down by grid, and ; blocked cells only reduce those counts. The binary-heap bound is therefore .
Implementation timing matters as much as the data structure. A vertex becomes
settled when it is removed as the minimum, not when it is first inserted into
the priority queue: insertion only records a tentative route that later
relaxations may improve. If an implementation inserts a fresh queue entry
instead of performing decrease-key, it must discard an extracted stale entry
whose key no longer equals d[v]. Starting with only the source in the heap, this version can
create and extract entries; the preceding count of at most V
extractions does not apply to it. Finally, if the smallest remaining key is
infinity, every still-unsettled vertex is unreachable from s, so the
algorithm may stop without inventing predecessor links.
Proof X-ray
Why an old heap entry is not a new settlement
Return to the v0 graph in the complete trace above, and use a min-heap that inserts a new pair (distance, vertex) for every strict improvement. Relaxing v0->v4(4) first inserts (4,v4). After extracting v2 at distance 2, relaxing v2->v4(1) improves d[v4] to 3 and inserts (3,v4); the old (4,v4) remains in the heap. With the trace's choice of v1 before v4 at the tied distance 3, (3,v4) is extracted and v4 is settled. The remaining old (4,v4) is extracted before the next valid distance 5; it is stale because 4 != d[v4] and must be discarded without settling or relaxing v4 again.
The distinction is the invariant behind the implementation: each finite unsettled estimate has a current heap entry, but the heap may also contain older entries. Discard stale entries until a current minimum unsettled estimate is obtained; for nonnegative edge weights, the safe-finalization proof above then applies. An insertion records a discovered path, not a final distance.
A path label must remember what remains possible
For the resource model below, take the integer budget .
In an ordinary shortest-path problem, a path that reaches vertex with smaller cost can replace a more expensive path to : both have exactly the same possible continuations. That replacement is the hidden reason it is sufficient to keep one distance per vertex. It can fail when using an edge also consumes a limited resource. Two arrivals at may have different amounts left, so the cheaper arrival can be unable to continue while the dearer one can reach the destination.
Suppose each directed edge has nonnegative cost and nonnegative integer resource use , and a route may use at most integer budget . Build an expanded graph with states , meaning that units have already been used. For each original edge , add
with cost whenever . Start at and take the minimum distance among for . Every feasible original walk determines such a state path, and every state path projects to a feasible original walk with the same cost. This two-way correspondence is the correctness bridge: an optimization algorithm on the expanded graph is now optimizing exactly the stated problem. With nonnegative costs Dijkstra applies to the expanded graph, not merely to the original vertices. Zero-resource edges are permitted; they do not invalidate Dijkstra when costs are nonnegative. A negative cost would invalidate that greedy guarantee.
For original vertices and edges the expanded graph has at most states and transitions. A binary heap gives a bound such as with adjacency lists. This is polynomial in the numerical value of , not necessarily in its bit length. If resource values are continuous, the finite table above is not justified without an additional discretization argument.
Worked problem 1: why the cheapest arrival can fail
Take directed edges labelled (cost, resource): , , and . Let . At , the direct route has cost 1 and has spent 3; the route costs 3 and has spent 0. The last edge needs 2 more units, so the cheap state cannot use it. The apparently inferior state reaches at total cost . It is the only feasible route to in this graph. Keeping only distance 1 at vertex and discarding the other arrival would incorrectly report failure.
A useful optimization is dominance: at the same vertex, a label with no greater cost and no more resource used dominates the other, because every continuation feasible from the latter is feasible from the former and costs no more. Equal labels can be merged. This argument requires the resource constraint and future costs to depend on the recorded state as specified; extra rules such as a visited-vertex restriction would require additional state.
An implementation need not materialize all transitions in memory. When it extracts , it can inspect the original adjacency list of and generate only transitions with . The maximum number of edge inspections is still proportional to if each expanded state is settled once. With an indexed binary heap supporting decrease-key, at most heap entries exist, giving the previously stated logarithmic factor. A lazy heap that inserts a new entry at every improvement needs a separate bound on the number of queued entries and must discard stale entries when popped. The data structure choice therefore belongs in the complexity statement, rather than being hidden behind the word “Dijkstra.”
Common mistakes
Common mistake
(Using Dijkstra on a negative edge)
Checking only for a negative cycle is not enough. Standard Dijkstra requires every edge weight to be nonnegative, even when the graph has no negative cycle.
Common mistake
(Treating discovered as settled)
A finite estimate means that one route is known. It does not become final until
the vertex is extracted as the minimum unsettled vertex. The complete trace's
three successive estimates for v5 make this distinction visible.
Common mistake
(Updating distance without predecessor)
Every strict improvement must update d[v] and pred[v] together. Otherwise
the printed distance and reconstructed path may describe different routes.
Common mistake
(Confusing shortest paths with BFS or an MST)
BFS minimizes the number of edges when edges are unweighted or all have the same cost. Dijkstra minimizes total nonnegative weight. An MST minimizes the sum of edges needed to connect all vertices; it does not minimize each route from a chosen source.
Common mistake
(Hiding a grid cost convention)
If numbers belong to cells, say whether entering or leaving a cell pays that number and whether the source is counted. The route and its total are not auditable until that convention is fixed.
Summary
d[v]is a tentative upper bound;pred[v]records the route realizing it.- Relaxation tests whether extending the path through
uimprovesv. - The minimum unsettled estimate may be finalized because all remaining edge weights are nonnegative.
- Dijkstra supports zero-weight edges but not negative edges.
- Predecessors reconstruct a shortest path after distances are settled.
- BFS is the simpler shortest-path tool for unweighted graphs; Dijkstra handles nonnegative unequal weights; MST algorithms solve a different optimization problem.
- Complexity depends on representation: with matrix/linear selection, or with adjacency lists and a binary heap using decrease-key.
Exercises
Quick check
(What two fields change after a successful relaxation?)
State both the numeric record and the path-reconstruction record.
Solution · Quick-check answer
A successful relaxation changes d[v] to the smaller candidate and changes
pred[v] to the vertex through which that candidate was obtained.
- Suppose
d[a]=4,w(a,b)=6,d[b]=13, andpred[b]=x. Relax(a,b). Then repeat whend[b]=9. - Using the complete trace, reconstruct the shortest paths from
v0tov3andv5, and verify both totals from the edge list. - Explain exactly which line of the safe-finalization proof fails in the graph
s->u(1),s->v(2),v->u(-2). - A graph is unweighted and represented by adjacency lists. Which algorithm is the natural shortest-path choice, and what is its running time?
- Under the weighted-grid convention above, what estimate is assigned to
(3,2)? Compare the two routes to that cell discussed in the example. - State one difference among the objectives of BFS shortest paths, Dijkstra shortest paths, and a minimum spanning tree.
Solutions
Solution · Guided solutions
- The candidate is
4+6=10. From13, update tod[b]=10andpred[b]=a. From9, make no change because10is not smaller. - For
v3, followv3 ← v4 ← v2 ← v0, reverse it, and obtainv0->v2->v4->v3with cost2+1+2=5. Forv5, appendv3->v5(1), giving total6. - The proof uses because the suffix from
ytouis assumed nonnegative. Here the suffix edgev->uhas weight-2, so a vertex with the larger prefix estimate can later create the cheaper path. - Use BFS. Its queue explores increasing edge-count layers in time.
- The estimate is
1+2+1+2=6along(1,1)->(1,2)->(2,2)->(3,2). The other incoming route,(1,1)->(2,1)->(3,1)->(3,2), costs1+4+1+2=8, so relaxation keeps6. - BFS minimizes edge count in an unweighted graph. Dijkstra minimizes total nonnegative path weight from one source. An MST minimizes the total weight of a spanning tree connecting all vertices, without optimizing every source-to-target route.