我目前是一名学生,正在开展一个小型项目。我的目标是能够确定两个给定城市之间的最短路径,但条件是需要经过指定数量的其他城市(或者您可能已经了解,我工作时会有一定数量的节点)用图表)。我已经按照dijkstra算法的基本标题编写了大部分程序(这是我唯一可以使用的算法),但发现自己无法指定需要经过的节点数量,你们其中一个人有没有我怎么想的呢?
import sys
def shortestpath(graph,start,end,visited=[],distances={},predecessors={}):
"""Find the shortest path between start and end nodes in a graph"""
# we've found our end node, now find the path to it, and return
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 graph[start]:
if neighbor not in visited:
neighbordist = distances.get(neighbor,sys.maxsize)
tentativedist = distances[start] + 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,sys.maxsize)) for k in 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 shortestpath(graph,closestnode,end,visited,distances,predecessors)
if __name__ == "__main__":
graph = {'Paris': { 'Marseille': 773, 'Lyon': 464, 'Toulouse': 677, 'Nice': 930, 'Nantes': 383, 'Angers': 294, 'Strasbourg': 492},
'Marseille': {'Paris': 773, 'Lyon': 314, 'Toulouse': 403, 'Nice': 207, 'Nantes': 985, 'Angers': 905, 'Strasbourg': 802},
'Lyon': {'Paris': 464, 'Marseille': 314, 'Toulouse': 537, 'Nice': 471, 'Nantes': 685, 'Angers': 596, 'Strasbourg': 493},
'Toulouse': {'Paris': 677, 'Marseille': 403, 'Lyon': 537, 'Nice': 561, 'Nantes': 585, 'Angers': 642, 'Strasbourg': 969},
'Nice': {'Paris': 930, 'Marseille': 207, 'Lyon': 471, 'Toulouse': 561, 'Nantes': 1143, 'Angers': 1063, 'Strasbourg': 785},
'Nantes': {'Paris': 383, 'Marseille': 985, 'Lyon': 685, 'Toulouse': 585, 'Nice': 1143, 'Angers': 91, 'Strasbourg': 866},
'Angers': {'Paris': 294, 'Marseille': 905, 'Lyon': 596, 'Toulouse': 642, 'Nice': 1063, 'Nantes': 91, 'Strasbourg': 777},
'Strasbourg': {'Paris': 492, 'Marseille': 802, 'Lyon': 493, 'Toulouse': 969, 'Nice': 785, 'Nantes': 866, 'Angers': 777}}