Shortest-Path Algorithms

Bellman-Ford Algorithm

The Bellman–Ford algorithm finds shortest paths from a starting node to all nodes of the graph.

The upgrade of BF Algorithm is Dijkstra’s Algorithm.

  • But it seems that there are good uses for bellman ford, because it works with negative weights while djikstra’s does not

Implementation

Code assumes that the graph is stored as an edge list edges that consists of tuples of the form , edge from node to node with weight .

for (int i = 1; i <= n; i++) distance[i] = INF;
distance[x] = 0;
for (int i = 1; i <= n-1; i++) {
	for (auto e : edges) {
		int a, b, w;
		tie(a, b, w) = e; // Unpack the tuple
		distance[b] = min(distance[b], distance[a]+w);
	}
}

Time complexity is

Negative Edges

Bellman-Ford works with negative edge weights (but no negative cycles). This doesn’t work with Dijkstra’s Algorithm.

From CS341

Shortest Path Faster Algorithm (SPFA) Algorithm

The SPFA algorithm (”Shortest Path Faster Algorithm”) is a variant of the Bellman–Ford algorithm, that is often more efficient than the original algorithm.

Proof

Let be the shortest path from to with at most edges.

If and before relaxation, then post-relaxation.