1

The main difference between Dijkstra algorithm and Bellman Ford algorithm that all texts (including CLRS) specify is that Dijkstra's algorithm need all non negative edge weights, while Bellman Ford algorithm can work with and detect -negative edge cycles.

However I feel a bit different, especially after coming across problem asking to build shortest path tree from node $a$ in following graph:

enter image description here

My shortest path tree after running Dijkstra came like this:

enter image description here

Then why texts say that Dijkstra need all non negative edge weights? I feel that it should be no -ve edge weight cycle reachable from source node. Am I correct with this? or am I missing something here?

Raphael
  • 73,212
  • 30
  • 182
  • 400
RajS
  • 1,737
  • 5
  • 28
  • 50

2 Answers2

4

Then why texts say that Dijkstra need all non negative edge weights?

Because it has to work for all cases, not only a few examples.

I feel that it should be no -ve edge weight cycle reachable from source node.

Try proving that claim and see where it leads. If you're successful, great; if not, trying to prove the opposite will fix your intuition.

See also here for a high-level argument.

The smallest example where Dijsktra fails has four nodes, no (directed) cycle at all, and no negative-value cycle:
example graph

Raphael
  • 73,212
  • 30
  • 182
  • 400
2

Raphael's answer is spot on, but let me offer some additional perspective as well.

Then why texts say that Dijkstra need all non negative edge weights?

Because we've been unable to prove it works otherwise.

In fact, imagine that negative edge-weights were allowed. In one extreme, this means that all edge weights can be negative. So we could take any graph that we want, make all weights equal to -1, and give it to the algorithm and find a shortest path between $s$ and $t$. This shortest path maximizes the length of the path (in terms of the number of edges), so we'll get a Hamiltonian path between $s$ and $t$ if it exists. But as far as we know, there is no polynomial-time algorithm for solving the problem!

Juho
  • 22,905
  • 7
  • 63
  • 117