我正在尝试在我的python代码上实现Dijkstra的算法,但我无法真正得到正确的算法。我使用的算法来自此YouTube链接:https://www.youtube.com/watch?v=pVfj6mxhdMw
所以基本上我的班级有这三个变量:
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
我还没有真正完成,因为我知道我在某个地方遗漏了一些东西。有人可以帮我这个。谢谢
答案 0 :(得分:0)
def dijkstra(self, start, end):
nodes = self.neighbours #{'A': {'B':2}, 'B': {'C':4}, ... }
unvisited = {n: 1000 for n in self.nodes} #unvisited node & distance
unvisited[start] = 0 #set start vertex to 0
visited = {} #list of all visited nodes
parent = {} #predecessors
while unvisited:
min_node = min(unvisited, key=unvisited.get) #get smallest distance
for neighbour in nodes[min_node].items():
if neighbour not in visited:
new_distance = unvisited[min_node] + nodes[min_node][neighbour]
if new_distance < unvisited[neighbour]:
unvisited[neighbour] = new_distance
parent[neighbour] = min_node
visited[min_node] = unvisited[min_node]
unvisited.pop(min_node)
print(parent, visited)