我有一个周期性的有向图。下面是图表作为python dict的表示
graph = {
'A': {'B': 5, 'D': 5, 'E': 7 },
'B': {'C': 4},
'C': {'D': 8, 'E': 2},
'D': {'C': 8, 'E': 6},
'E': {'B': 3}
}
我写了一个Dijkstra最短路径的简单实现。这似乎适用于两点。以下是我的实施。
def shortestpath(self, start, end, visited=[],distances={},predecessors={}):
# initialize a big number
maxint = 10000
if start==end:
path=[]
while end != None:
path.append(end)
end=predecessors.get(end, None)
return distances[start], path[::-1]
# detect if it's the first time through, set current distance to zero
if not visited: distances[start]=0
# process neighbors as per algorithm, keep track of predecessors
for neighbor in self.graph[start]:
if neighbor not in visited:
neighbordist = distances.get(neighbor,maxint)
tentativedist = distances[start] + self.graph[start][neighbor]
if tentativedist < neighbordist:
distances[neighbor] = tentativedist
predecessors[neighbor]=start
# neighbors processed, now mark the current node as visited
visited.append(start)
# finds the closest unvisited node to the start
unvisiteds = dict((k, distances.get(k,maxint)) for k in self.graph if k not in visited)
closestnode = min(unvisiteds, key=unvisiteds.get)
# now we can take the closest node and recurse, making it current
return self.shortestpath(closestnode,end,visited,distances,predecessors)
现在这个简单的实现似乎有效。例如,如果我做这样的事情
shortestpath('A', 'C')
它会给我路径和最短的重量
(9,['A','B','C'])
在这种情况下。
但是,每当我shortestpath('B', 'B')
程序中断时。
现在有B to B
的最短路径,因为它是一个循环图,路径是B-C-E-B。我只是不知道如何检查并相应地修改Dijktra的算法,以检查像这样的循环情况。任何建议都非常感谢。谢谢:))