[英]Dijkstra's Algorithm Implementation in Python - How Does it Work?
我可以在紙上使用Dijkstra的算法使用以下英語算法來查找最短路徑:
步驟1:將永久標簽和順序分配給起始節點
步驟2:將臨時標簽分配給起始節點直接到達的所有節點
步驟3:選擇最低的臨時標簽並將其永久化
步驟4:將訂單分配給節點
步驟5:為從新的永久節點直接到達的節點更新並分配臨時標簽
步驟6:重復步驟3、4和5,直到將目標節點設為永久節點
我已經搜索了Python實現,其中許多都非常復雜或使用了我不熟悉的數據結構。 最終我找到了下面的那個。 我花了很多時間在Python可視化工具中追蹤它的執行情況,我可以大致了解它的工作原理,但對我來說還沒有點擊。
有人可以解釋一下代碼與英語算法的關系嗎? 例如,“前輩”的概念與英文版中的“永久標簽”有何關系?
from math import inf
graph = {'a':{'b':10,'c':3},'b':{'c':1,'d':2},'c':{'b':4,'d':8,'e':2},'d':{'e':7},'e':{'d':9}}
def dijkstra(graph,start,goal):
shortest_distance = {}
predecessor = {}
unseenNodes = graph
infinity = inf
path = []
for node in unseenNodes:
shortest_distance[node] = infinity
shortest_distance[start] = 0
# Determine which is minimum node. What does that mean?
while unseenNodes:
minNode = None
for node in unseenNodes:
if minNode is None:
minNode = node
elif shortest_distance[node] < shortest_distance[minNode]:
minNode = node
for edge, weight in graph[minNode].items():
if weight + shortest_distance[minNode] < shortest_distance[edge]:
shortest_distance[edge] = weight + shortest_distance[minNode]
predecessor[edge] = minNode
unseenNodes.pop(minNode)
currentNode = goal
while currentNode != start:
try:
path.insert(0,currentNode)
currentNode = predecessor[currentNode]
except KeyError:
print('Path not reachable')
break
path.insert(0,start)
if shortest_distance[goal] != infinity:
print('Shortest distance is ' + str(shortest_distance[goal]))
print('And the path is ' + str(path))
dijkstra(graph, 'a', 'b')
Dijkstra的算法與prim的最小生成樹算法相同。 像Prim的MST一樣,我們以給定源作為根生成最短路徑樹。 我們維護兩組,一組包含最短路徑樹中包含的頂點,另一組包含尚未包含在最短路徑樹中的頂點。 在算法的每個步驟中,我們都找到一個頂點,該頂點在另一個集合中(尚未包括在內),並且與源的距離最小。
import sys
class Graph():
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)]
for row in range(vertices)]
def printSolution(self, dist):
print("Vertex tDistance from Source")
for node in range(self.V):
print(node, "t", dist[node])
def minDistance(self, dist, sptSet):
min = sys.maxint
for v in range(self.V):
if dist[v] < min and sptSet[v] == False:
min = dist[v]
min_index = v
return min_index
def dijkstra(self, src):
dist = [sys.maxint] * self.V
dist[src] = 0
sptSet = [False] * self.V
for cout in range(self.V):
u = self.minDistance(dist, sptSet)
sptSet[u] = True
for v in range(self.V):
if self.graph[u][v] > 0 and sptSet[v] == False and \
dist[v] > dist[u] + self.graph[u][v]:
dist[v] = dist[u] + self.graph[u][v]
self.printSolution(dist)
g = Graph(9)
g.graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0],
[4, 0, 8, 0, 0, 0, 0, 11, 0],
[0, 8, 0, 7, 0, 4, 0, 0, 2],
[0, 0, 7, 0, 9, 14, 0, 0, 0],
[0, 0, 0, 9, 0, 10, 0, 0, 0],
[0, 0, 4, 14, 10, 0, 2, 0, 0],
[0, 0, 0, 0, 0, 2, 0, 1, 6],
[8, 11, 0, 0, 0, 0, 1, 0, 7],
[0, 0, 2, 0, 0, 0, 6, 7, 0]]
g.dijkstra(0)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.