如何查找两个图形节点之间的所有路径,如下图所示?我尝试了广度优先搜索(BFS)算法,但是虽然它可以找到所有的点,但它找不到从(S)tart到(E)nd的所有路径。我还尝试了深度优先搜索(DFS),它更接近了。然而,当应用这种策略时,因为有一个封闭的列表,它只会找到一条路径,可能是红线,因为紫色和绿色正在穿过该区域的封闭列表,这些路径将被忽略。
我想知道如何从(S)馅饼到(E)nd获得所有路径。在下面的情况中:
答案 0 :(得分:0)
Dijkstra's Algorithm(这里,在Python中)效果很好:
def find_all_paths(graph, start, end, path=[]):
path = path + [start]
if start == end:
return [path]
if start not in graph:
return []
paths = []
for node in graph[start]:
if node not in path:
newpaths = find_all_paths(graph, node, end, path)
for newpath in newpaths:
paths.append(newpath)
return paths
def min_path(graph, start, end):
paths=find_all_paths(graph,start,end)
mt=10**99
mpath=[]
print '\tAll paths:',paths
for path in paths:
t=sum(graph[i][j] for i,j in zip(path,path[1::]))
print '\t\tevaluating:',path, t
if t<mt:
mt=t
mpath=path
e1=' '.join('{}->{}:{}'.format(i,j,graph[i][j]) for i,j in zip(mpath,mpath[1::]))
e2=str(sum(graph[i][j] for i,j in zip(mpath,mpath[1::])))
print 'Best path: '+e1+' Total: '+e2+'\n'
if __name__ == "__main__":
graph = {'D1': {'D2':1, 'C1':1},
'D2': {'C2':1, 'D1':1},
'C1': {'C2':1, 'B1':1, 'D1':1},
'C2': {'D2':1, 'C1':1, 'B2':1},
'B1': {'C1':1, 'B2':1},
'B2': {'B1':1, 'A2':1, 'C2':1},
'A2': {'B2':1, 'A1':1},
'A1': {'A2':1}}
min_path(graph,'D1','A1')
打印:
All paths: [['D1', 'C1', 'C2', 'B2', 'A2', 'A1'], ['D1', 'C1', 'B1', 'B2', 'A2', 'A1'], ['D1', 'D2', 'C2', 'C1', 'B1', 'B2', 'A2', 'A1'], ['D1', 'D2', 'C2', 'B2', 'A2', 'A1']]
evaluating: ['D1', 'C1', 'C2', 'B2', 'A2', 'A1'] 5
evaluating: ['D1', 'C1', 'B1', 'B2', 'A2', 'A1'] 5
evaluating: ['D1', 'D2', 'C2', 'C1', 'B1', 'B2', 'A2', 'A1'] 7
evaluating: ['D1', 'D2', 'C2', 'B2', 'A2', 'A1'] 5
Best path: D1->C1:1 C1->C2:1 C2->B2:1 B2->A2:1 A2->A1:1 Total: 5
如果更改dict中的数字(在这种情况下,所有1
的成本相同)将改变使用该路径段的“成本”。有an example using train routes。