尝试在用户定义的图形中实现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
答案 0 :(得分:1)
你的问题在这一行:
if Distances[NeighbourID] < Distances[Node] + NeighbourValue:
将小于号更改为大于号,因为您只想用较小的符号替换Neighbor
的距离。此外,您还必须确保在尝试查找最小距离时将Distance[i] == -1
视为单独的案例。
固定代码:
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 Distances[TempNode] == -1: continue
if ShortestDistance == None:
ShortestDistance = Distances[TempNode]
Node = TempNode
elif Distances[TempNode] < ShortestDistance:
ShortestDistance = Distances[TempNode]
Node = TempNode
if ShortestDistance is None: break
UnseenNodes.remove(Node)
for Neighbour, NeighbourValue in self.NodeList[Node].Connections.items():
NeighbourID = Neighbour.GetID()
print NeighbourID
if Distances[NeighbourID] == -1 or 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