0
試圖在用戶定義的圖中實現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
順便說一句你試圖調試它?例如,Pycharm具有很好的python調試器,可以將斷點放到每個步驟並進行更多調查。 – pagep