Dijkstra’s Algorithm fails when in a graph we have edges with negative weights. However, to this rule there is an exception: If In a directed acyclic graph only the edges that leave the source node are negative (all the other edges are positive), then we can successfully use Dijkstra’s Algorithm.
Now my question is, what if in the above exception the graph has a cycle? I believe Dijkstra won’t work, but I cannot come up with an example of a directed graph that has cycles, and the only negative edges are those leaving the source node which does not work with Dijkstra. Anyone can suggest an example?
In the scenario you describe, Dijkstra’s algorithm will work just fine.
The reason why it fails in the general case with negative weight since it greedily chooses which node to “close” at each step, and a closed node is never reopened.
Now, assume the source
shaskout edges, tokdifferent nodes.Let the order of them be
v_1, v_2, ..., v_k(v_1being the smallest). Note that for eachv_i,v_jsuch thati < j– there will be no path fromstov_ithroughv_jwith a “better” cost thenv_i, thus – the order of investigating these first nodes will never change. (and since it doesn’t change, no way a later node will be entered to “closed” before the shortest path is indeed found).Thus, at overall – no harm is done – once an edge is in the “closed” – you will never find a “shorter” path to it, since the negative edges are only from the source.
In here I assume the
sourcein your question meansd_in(source)=0, same as a “source” in a DAG.If you mean out of the source vertex, it could be a problem since look at a 2 vertices graph such that
w(s,t) = -2, w(t,s)=1– there is a negative cycle in the graph. So, in order to the above explanation to work – you must assumed_in(s) = 0