129
Negative-weight edges
So it makes sense to do the second trade—Rama gets $2 back that way!
Now,
if you remember, Rama can trade the poster for the drums. There
are two paths he could take.
The second path costs him $2 less, so he should take that path, right?
Well, guess what? If you run Dijkstra’s
algorithm on this graph, Rama
will take the wrong path. He’ll take the longer path.
You can’t use
Dijkstra’s algorithm if you have negative-weight edges.
Negative-weight
edges break the algorithm. Let’s see what happens when you run
Dijkstra’s algorithm on this. First, make the table of costs.
Next, find the lowest-cost node, and update the costs for its neighbors.
In this case, the poster is the lowest-cost node. So, according to
Dijkstra’s algorithm,
there is no cheaper way to get to the poster than
paying $0
(you know that’s wrong!). Anyway, let’s update the costs for
its neighbors.
Ok, the drums have a cost of $35 now.