22/40
Part 4 of 7 · A park with no cyclesLearn

With a cycle, pick the tool by what you optimize

A cycle doesn't end the question. It changes the tool.

  • The cheapest route, with costs that are never negative: Dijkstra's algorithm.
  • The cheapest route with some negative costs: Bellman-Ford, O(VE)O(VE), which also detects a negative cycle. The booksite names the two easy cases: all weights nonnegative, or no cycles. Bellman-Ford covers the rest, as long as no cycle is negative.
  • The best simple path on a small graph: put a bitmask of the junctions visited into the state, for O(2VV2)O(2^V V^2). That's fine up to about 20 junctions. The follow-ups show the bitmask.
  • Something in the state that only grows, like minutes or steps. Then a move can never return to the same state, and the cyclic graph becomes a DAG of states. The worked example does exactly that.