Professional Documents
Culture Documents
Single Source Shortest Paths
Single Source Shortest Paths
Relax Relax
2 2
5 7 5 6
David Luebke
The Bellman-Ford algorithm
• BELLMAN-FORD(G, w, s)
• 1 INITIALIZE-SINGLE-SOURCE(G, s)
• 2 for i ← 1 to |V[G]| - 1
• 3 do for each edge (u, v) ε E[G]
• 4 do RELAX(u, v, w)
• 5 for each edge (u, v) ε E[G]
• 6 do if d[v] > d[u] + w(u, v)
• 7 then return FALSE
• 8 return TRUE
The Bellman-Ford algorithm
Dijkstra's algorithm
• Dijkstra's algorithm solves the single-
source shortest-paths problem on a
weighted, directed graph G = (V, E) for the
case in which all edge weights are
nonnegative.
• the running time of Dijkstra's algorithm is
lower than that of the Bellman-Ford
algorithm.
Dijkstra's algorithm
DIJKSTRA(G, w, s)
• 1 INITIALIZE-SINGLE-SOURCE(G, s)
• 2S←Ø
• 3 Q ← V[G]
• 4 while Q ≠ Ø
• 5 do u ← EXTRACT-MIN(Q)
• 6 S ← SU {u}
• 7 for each vertex v ε Adj[u]
• 8 do RELAX(u, v, w)
Dijkstra's algorithm
Single-source shortest paths in directed
acyclic graphs
DAG-SHORTEST-PATHS(G, w, s)
• 1 topologically sort the vertices of G
• 2 INITIALIZE-SINGLE-SOURCE(G, s)
• 3 for each vertex u, taken in topologically sorted
order
• 4 do for each vertex v ε Adj[u]
• 5 do RELAX(u, v, w)
The total running time of this algorithm is Θ(V + E).
Single-source shortest paths in directed
acyclic graphs
All-Pairs Shortest Paths
• In this case we consider the problem of finding shortest
paths between all pairs of vertices in a graph.
• we are given a weighted, directed graph G = (V, E) with
a weight function w : E → R that maps edges to real-
valued weights. We wish to find, for every pair of vertices
u, v εV , a shortest (least-weight) path from u to v,
where the weight of a path is the sum of the weights of
its constituent edges.
• We typically want the output in tabular form: the entry in
u's row and v's column should be the weight of a
shortest path from u to v.
All-Pairs Shortest Paths