Negative weights using Dijkstra's Algorithm -
i trying understand why dijkstra's algorithm not work negative weights. reading example on shortest paths, trying figure out following scenario:
2 a-------b \ / 3 \ / -2 \ / c
from website:
assuming edges directed left right, if start a, dijkstra's algorithm choose edge (a,x) minimizing d(a,a)+length(edge), namely (a,b). sets d(a,b)=2 , chooses edge (y,c) minimizing d(a,y)+d(y,c); choice (a,c) , sets d(a,c)=3. never finds shortest path b, via c, total length 1.
i can not understand why using following implementation of dijkstra, d[b] not updated 1
(when algorithm reaches vertex c, run relax on b, see d[b] equals 2
, , therefore update value 1
).
dijkstra(g, w, s) { initialize-single-source(g, s) s ← Ø q ← v[g]//priority queue d[v] while q ≠ Ø u ← extract-min(q) s ← s u {u} each vertex v in adj[u] relax(u, v) } initialize-single-source(g, s) { each vertex v v(g) d[v] ← ∞ π[v] ← nil d[s] ← 0 } relax(u, v) { //update if found strictly shortest path if d[v] > d[u] + w(u,v) d[v] ← d[u] + w(u,v) π[v] ← u update(q, v) }
thanks,
meir
the algorithm have suggested indeed find shortest path in graph, not graphs in general. example, consider graph:
assume edges directed left right in example,
your algorithm work follows:
- first, set
d(a)
zero
, other distancesinfinity
. - you expand out node
a
, settingd(b)
1
,d(c)
zero
, ,d(d)
99
. - next, expand out
c
, no net changes. - you expand out
b
, has no effect. - finally, expand
d
, changesd(b)
-201
.
notice @ end of this, though, d(c)
still 0
, even though shortest path c
has length -200
. algorithm fails accurately compute distances in cases. moreover, if store pointers saying how each node start node a
, you'd end taking wrong path c
a
.
Comments
Post a Comment