1
我想在我的python代碼上實現Dijkstra的算法,但我不能真正得到正確的算法。我使用的算法與此YouTube鏈接:https://www.youtube.com/watch?v=pVfj6mxhdMwDijkstra在python中的算法
所以基本上我的類有這3個變量:
self.nodes = [] #a,b,c
self.neighbours = {} # a:[b,c], b:[c], c:[a]
self.weights = {} #[a,b] = 2, [a,c] = 5
這裏是我部分地使用在視頻中提供的算法來實現我的最短路徑功能:
def dijkstra(self, start, end):
nodes = {}
for n in self.nodes:
if n == start:
nodes[n] = 0
else:
nodes[n] = float('inf')
unvisited = self.neighbours
visited = []
current_node = start
current_distance = 0
while unvisited:
for n in unvisited[current_node]:
print(n)
#calc_weight = nodes[n] + self.weights[n, current_node]
#if (unvisited[n] is None or calc_weight > nodes[n]):
#nodes[n] = calc_weight
visited.append(current_node)
del unvisited[current_node]
if not unvisited: break
我沒有真正完成,因爲我知道我錯過了什麼地方的東西。有人可以幫助我這個。謝謝
維基百科:[Dijkstra算法](https://en.wikipedia.org/wiki/Dijkstra's_algorithm)。甚至有僞碼。 – furas
你問題解決了嗎? – Shasha99
@ Shasha99沒有。我似乎無法得到正確的算法。 以前的評論沒有幫助,有人讓我找到了另一種算法,它不是真正的答案,而第二種算法讓我引發了一個hello world程序。 –