Apply Dijkstra's algorithm in a undirected graph with negative weights

827 views Asked by At

Can anyone apply Dijkstra's algorithm in the undirected graph with negative weights above? Even if the algorithm fails.

Adjancency's list:

A -> (B, 3), (C, 2), (D, 4)
B -> (A, 3), (C, -2), (F, 6)
C -> (A, 2), (B, -2), (E, 5)
D -> (A, 4), (E, 3), (F, 2)
E -> (C, 5), (D, 3), (F, -2)
F -> (B, 6), (D, 2), (E, -2)
1

There are 1 answers

0
Speed8ump On

Seed the traversal list with source node A, and it's cost with 0. Add an infinite cost for every other node:

{}, [A=0, B=inf, C=inf, D=inf, E=inf, F=inf]

Then take the lowest current cost item (I'll call it L) and "accept" it into the final cost set (the first pass case has L=source node (A), with a cost of 0). Check each edge from L calculating the total cost to follow that edge. If that total cost is less than the traversal list current cost, update the traversal list with the new lower cost.

{A=0}, [B=0+3, C=0+2, D=0+4, E=inf, F=inf]

C is now the lowest cost node in the traversal list, so accept C with a cost of 2:

{A=0, C=2}, [B=2-2=0, D=4, E=2+5=7, F=inf]

It's really easy to detect the problem at this point because I just put a cost in the traversal list that is less less than the cost of the node I just accepted (C). But, unencumbered by reason or logic we carry on:

{A=0, C=2, B=0}, [D=4, E=7, F=0+6]
{A=0, C=2, B=0, D=4}, [E=7, F=6]
{A=0, C=2, B=0, D=4, E=7}, [F=7-2=5]
{A=0, C=2, B=0, D=4, E=7, F=5}

Due to the negative cost loops in the graph, the correct final cost array should be:

{A=-inf, B=-inf, C=-inf, D=-inf, E=-inf, F=-inf}

But we already knew that Dijkstra's fails when the graph has negative cost loops...right?