Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

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

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...