我试图在路径列表里面找到最短的列表,但是我收到一个错误('NoneType'对象在Python中不是可迭代的错误)。这个函数是用于 "图模式 "或 "搜索算法 "寻找通往目标的最短路径。 请让我知道我在这里做错了什么。 谢谢!我正试图找到最短的路径。
graph = {'A':['B','C'],'B':['F','D','I'],'C':['D','E','G'],'D':['H'],'F':['I'],'E':['G'],'I':['H'],'D':['H'],'H':['G']}
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)
minList=min(paths, key= len)
print(minList)
顶点 G
遗漏在您的邻接列表中。在修改您的邻接列表并返回 paths
的函数,你就能得到正确的结果。
graph = {'A':['B','C'],'B':['F','D','I'],'C':['D','E','G'],'D':['H'],'F':['I'],'E':['G'],'I':['H'],'D':['H'],'H':['G'], 'G':[]}
def find_all_paths(graph, start, end, path=[]):
path = path + [start]
if start == end:
return [path]
paths = []
for node in graph[start]:
if node not in path:
newpaths = find_all_paths(graph, node, end, path)
if newpaths:
for newpath in newpaths:
paths.append(newpath)
return paths
graph
{'A': ['B', 'C'],
'B': ['F', 'D', 'I'],
'C': ['D', 'E', 'G'],
'D': ['H'],
'F': ['I'],
'E': ['G'],
'I': ['H'],
'H': ['G'],
'G': []}
paths = find_all_paths(graph,'A', 'H',[])
输出。
paths
[['A', 'B', 'F', 'I', 'H'],
['A', 'B', 'D', 'H'],
['A', 'B', 'I', 'H'],
['A', 'C', 'D', 'H']]
为了找到一条最短路径,你可以使用
min(paths, key=len)