Bellman-Ford

Finds the shortest distance from a start vertex to every other vertex, even with negative weights, and reports a negative cycle when the start can reach one.

Time complexity O(V·E), gograph function path.BellmanFord.

Major currencies

Six major currencies and the rates a dealer quotes between them. Each edge is a trade, and its weight is minus the natural log of the exchange rate, so the shortest path is the best rate. Dollars buy more francs through EUR than directly. The rates are illustrative and close to market rates, and every loop of trades loses a little to the spread.

A directed, weighted graph with 6 vertices and 20 edges.

How much of each currency can a dollar buy at the best rate, trading through other currencies when that pays more?

Use it in Go

dist, err := path.BellmanFord(g, "USD")
if err != nil {
	return err // path.ErrNegativeWeightCycle
}
fmt.Println(dist["GBP"])

Example graphs

More in Shortest paths

  • Dijkstra: Finds the shortest distance from a start vertex to every other vertex when no edge weight is negative.
  • Floyd-Warshall: Finds the shortest distance between every pair of vertices, even with negative weights, by letting paths stop at one more vertex in each round.

All algorithms