Bellman-Ford Algorithm

Shortest path with negative edge weights and source vertex

init d(s) = 0, d(v) = +INF for every vertex
for j = 1,..., n
	for (u, v) in edges
		if (u, v) incorrect, correct it
if any d(v) changed on nth iteration
	output negative cycle
else output d(v) for every vertex

Definition of correctness

An edge is correct if it’s actually the shortest path. Else needs update.

All-Pairs Shortest Paths

Given digraph with an negative cycle, compute shortest path distances for every v Compute Bellman-Ford n times:

Can we do better? If non-negative edge weights, run Djikstra’s n times

Bad idea: adding constant to all edge weights to make them non-negative

Adding greatest negative number to all edges such that they’re all non-negatives

I originally thought you couldn’t do this because negative edges have different behavior

  • Actually because paths with more edges used will be more proportionally increased than paths with less edges, so it doesn’t preserve shortest path

Better idea: feasible potential

Given digraph G with weights w and function

A transformation of weights that preserves the weights (not just adding a constant C to all).

Telescoping sum:

For any vertex the function defines a feasible potential. So feasible potential is computed shortest path.

Johnson’s Algorithm

For all-pairs shortest paths:

  1. Fix , run Bellman-Ford to compute for every vertex
  2. Transform weights where where
  3. Compute all shortest paths by running Djikstra’s n times with weights
  4. Output

Slight issue: what if there’s no path from s to v (disconnected graph)

  • Add connecting edges with largest edge weight (greater than the sum of all pos edge weights in graph)

DP Solution: Floyd-Warshall Algorithm

Compute APSP iteratively by using intermediate vertices (from u to v)

Cases based on whether using current vertex or not. Take minimum of cases for shortest path:

Case 1: use the vertex, so compute shortest path from source to curr and curr to target`

Can probably memoize with hashmap