Search code examples
algorithmdijkstranegative-numberbellman-ford

Negative Cycles with Dijkstra's Algorithm


So I completely understand why negative edge weights will not work with Dijkstra's algorithm with an example like so:

       A
      / \
     /   \
    /     \
   5       2
  /         \
  B--(-10)-->C

However, I have read that "if there is any negative cycle in graph you would never stop updating distance in vertices. This will cause a infinite loop." I don't understand how this would be the case if we declare vertices "done" when we visit them. How could we ever enter a cycle if we cannot revisit vertices we have already visited?


Solution

  • The version that you describe will indeed avoid loops. It can also fail to discover the correct lowest cost path in cases where the lowest cost path has negative edges, but there is a more direct route without them.