一直在尝试在用户定义图中实现Dijkstras算法。但它总是给出错误的解决方案。不管怎样你们能帮我看看吗?你知道吗
def ShortestPath(self, Source, Dest):
Distances = {}
Previous = {}
for EachNode in self.NodeList.keys():
Distances[EachNode] = -1
Previous[EachNode] = ""
Distances[Source] = 0
UnseenNodes = self.NodeList.keys()
while len(UnseenNodes) > 0:
ShortestDistance = None
Node = ""
for TempNode in UnseenNodes:
if ShortestDistance == None:
ShortestDistance = Distances[TempNode]
Node = TempNode
elif Distances[TempNode] < ShortestDistance:
ShortestDistance = Distances[TempNode]
Node = TempNode
UnseenNodes.remove(Node)
for Neighbour, NeighbourValue in self.NodeList[Node].Connections.items():
NeighbourID = Neighbour.GetID()
print NeighbourID
if Distances[NeighbourID] < Distances[Node] + NeighbourValue:
Distances[NeighbourID] = Distances[Node] + NeighbourValue
Previous[NeighbourID] = Node
print Previous
Path = []
Node = Dest
while not (Node == Source):
if Path.count(Node) == 0:
Path.insert(0,Node)
Node = Previous[Node]
else:
break
Path.insert(0,Source)
print Path
你的问题是:
将小于号改为大于号,因为您只想用较小的距离替换
Neighbor
的距离。此外,当您试图找到最小距离时,还必须确保将Distance[i] == -1
作为一个单独的案例来处理。你知道吗固定代码:
相关问题 更多 >
编程相关推荐