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.BellmanFordPaths.

path.BellmanFord returns the same distances as a map, without the routes.

How it works

Bellman-Ford starts like Dijkstra, with 0 at the start and infinity everywhere else, but it doesn't take vertices in order of distance. It goes through every edge, and when an edge gives its end a shorter distance, it lowers that distance. It repeats this pass one time fewer than there are vertices. A shortest path that doesn't repeat a vertex has at most that many edges, so after the last pass every distance is final.

Then it makes one more pass. If an edge can still shorten a distance, the start can reach a cycle whose weights add up to less than zero. Such a graph has no shortest path, since each trip around the cycle makes the path shorter, and path.BellmanFordPaths returns ErrNegativeWeightCycle. It needs a directed, weighted graph and costs O(V·E). path.NegativeCycle then returns one such cycle. It searches the whole graph rather than what one start reaches, so on a graph with more than one it can return a cycle other than the one the start runs into.

When there is no negative cycle, Distance and PathTo on the result give each distance and the route there, start first, and report false for a vertex out of reach. Of two routes that are equally short, PathTo returns the one with the fewest edges.

Use it when some weights are negative, such as refunds, rewards or the negative logarithms of exchange rates, where a negative cycle is a chance for arbitrage. When no weight is negative, Dijkstra gives the same distances faster.

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?

At the best rates, 1 USD buys 149.85 JPY, 1.3652 CAD, 0.90818 EUR, 0.84745 CHF and 0.76808 GBP.

Step by step

  1. Every distance starts at ∞, except USD, which is 0. Bellman-Ford checks all 20 edges in each of 5 passes, one fewer than the 6 vertices, then once more to look for a negative cycle.
  2. Pass 1. USD to EUR at 0.90818: 0 + 0.0963 = 0.0963, so EUR's distance becomes 0.0963: 1 USD buys 0.90818 EUR this way.
  3. Pass 1. USD to GBP at 0.76808: 0 + 0.2639 = 0.2639, so GBP's distance becomes 0.2639: 1 USD buys 0.76808 GBP this way.
  4. Pass 1. USD to JPY at 149.85: 0 - 5.0096 = -5.0096, so JPY's distance becomes -5.0096: 1 USD buys 149.85 JPY this way.
  5. Pass 1. USD to CHF at 0.8449: 0 + 0.1685 = 0.1685, so CHF's distance becomes 0.1685: 1 USD buys 0.8449 CHF this way.
  6. Pass 1. USD to CAD at 1.3632: 0 - 0.3098 = -0.3098, so CAD's distance becomes -0.3098: 1 USD buys 1.3632 CAD this way.

7 more steps lead to the last one:

  1. Extra pass. No edge gives a shorter distance, so there is no negative cycle. Every distance from USD is final.

Use it in Go

paths, err := path.BellmanFordPaths(g, "USD")
if errors.Is(err, path.ErrNegativeWeightCycle) {
	loop, _ := path.NegativeCycle(g)
	for _, v := range loop {
		fmt.Println(v.Label())
	}
	return err
}
if err != nil {
	return err
}
dist, ok := paths.Distance("GBP")
if !ok {
	return nil // out of reach
}
route, _ := paths.PathTo("GBP")
fmt.Println(dist)
for _, v := range route {
	fmt.Println(v.Label())
}

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.
  • A*: Finds the quickest route from one vertex to another, looking first where a guess of the time left says the goal is, so it settles far fewer vertices than Dijkstra.
  • Bidirectional search: Finds the quickest route from one vertex to another by searching forward from the start and backward from the goal at once, until the two searches meet.
  • k shortest paths: Finds the k quickest routes from one vertex to another that don't repeat a vertex, quickest first, the way a navigation app offers a few routes.
  • Beam search: Looks for a route from one vertex to another while keeping only the few best partial paths at each step, so its memory and time stay bounded, at the cost of sometimes missing the best route.
  • Multi-source Dijkstra: Finds the nearest of several sources for every vertex, and the distance from it, in one search.
  • k-center: Chooses k centers so that the vertex farthest from its nearest center is as near as it can make it.
  • 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