Generic S.P. Algorithm
Initialize: for v in V:
d[v] ← ∞
Π[v] ← NIL
d[s] ← 0
Main: Repeat
select edge (u, v)
Relax edge (u, v): if d[v] > d[u] + w(u, v):
d[v] ← d[u] + w(u, v)
Π[v] ← u
until you can’t relax any more edges or you’re tired or . .
- Complexity could be exp time
- The algorithm will continually relax edges when there are negative cycles present.
Bellman-Ford (G, W, s)
Initializa():
for i = 1 to |v| -1:
for each edge(u, v) in E
Relax(u, v, w)
for each edge (u, v) in E:
if d[v] > d[u] + w(u, v)
then report -ve cycle exists
Theorem:
If G = (V, E) contains no negative weight cycles, then after Bellman-Ford executes d[v] = δ(s, v) for all v ∈ V .
Corollary:
If a value d[v] fails to converge after |V | − 1 passes, there exists a negative-weight cycle reachable from s.
Longest Simple Path and Shortest Simple Path
Finding the longest simple path in a graph with non-negative edge weights is an NP-hard problem, for which no known polynomial-time algorithm exists. Suppose one simply negates each of the edge weights and runs Bellman-Ford to compute shortest paths. Bellman-Ford will not necessarily compute the longest paths in the original graph, since there might be a negative-weight cycle reachable from the source, and the algorithm will abort. Similarly, if we have a graph with negative cycles, and we wish to find the longest simple path from the source s to a vertex v, we cannot use Bellman-Ford. The shortest simple path problem is also NP-hard.