【演算法日記】貝爾曼-福德演算法

來源:互聯網
上載者:User

標籤:a演算法   log   rom   return   images   image   存在   for   print   

 

 

如使用Dijkstra演算法將無法擷取到最短路徑

1.A->C->D   5

2.A->B...沒有

最近路徑為5.但是實際上B->C的路徑為-2. A->B->C->D的最短開銷為3

Dijkstra演算法無法判斷含負權邊的圖的最短路。如果遇到負權,在沒有負權迴路存在時(負權迴路的含義是,迴路的權值和為負。)即便有負權的邊,也可以採用貝爾曼-福德演算法演算法正確求出最短路徑。

 

演算法實現
 1 def bellman_ford( graph, source ):   2        3     distance = {}   4     parent = {}   5        6     for node in graph:   7         distance[node] = float( ‘Inf‘ )   8         parent[node] = None   9     distance[source] = 0  10   11     for i in range( len( graph ) - 1 ):  12         for from_node in graph:  13             for to_node in graph[from_node]:  14                 if distance[to_node] > graph[from_node][to_node] + distance[from_node]:  15                     distance[to_node] = graph[from_node][to_node] + distance[from_node]  16                     parent[to_node] = from_node  17   18     for from_node in graph:  19         for to_node in graph[from_node]:  20             if distance[to_node] > distance[from_node] + graph[from_node][to_node]:  21                 return None, None  22   23     return distance, parent  24   25 def test():  26     graph = {  27         ‘a‘: {‘b‘: -1, ‘c‘:  4},  28         ‘b‘: {‘c‘:  3, ‘d‘:  2, ‘e‘:  2},  29         ‘c‘: {},  30         ‘d‘: {‘b‘:  1, ‘c‘:  5},  31         ‘e‘: {‘d‘: -3}  32     }  33     distance, parent = bellman_ford( graph, ‘a‘ )  34     print distance  35     print parent  36   37 if __name__ == ‘__main__‘:  38     test()  

 

【演算法日記】貝爾曼-福德演算法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.