python元组字典中的DFS
所以我花了5个小时在谷歌上搜索DFS、BFS、A*、贝尔曼福特和其他公司 我有python元组字典中的DFS,python,algorithm,graph,depth-first-search,Python,Algorithm,Graph,Depth First Search,所以我花了5个小时在谷歌上搜索DFS、BFS、A*、贝尔曼福特和其他公司 我有roads=[('a',[('b',5.0),('c',8.0)],('b',[('a',5.0),('d',6.0)],('c',[('a',8.0),('d',2.0)],('d',[('b',6.0),('c',2.0),('e',12.0),('f',2.0)],('e',['d',12.0),(', ('g',3.0)],('f',[('d',2.0),('g',7.0)],('g',[('e',3.0),(
roads=[('a',[('b',5.0),('c',8.0)],('b',[('a',5.0),('d',6.0)],('c',[('a',8.0),('d',2.0)],('d',[('b',6.0),('c',2.0),('e',12.0),('f',2.0)],('e',['d',12.0),(',
('g',3.0)],('f',[('d',2.0),('g',7.0)],('g',[('e',3.0),('f',7.0)]]
加权字典。我发现这个代码:
def find_all_paths(graph, start, end, path=[]):
path = path + [start]
if start == end:
return [path]
if not start 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
它从未在道路上找到起点,并返回[]
我太迷路了。我了解这些算法的功能,但不知道如何编写它们。我只想找到最短的路 您复制的代码无法解决您的问题。首先,请注意,它的名称告诉您它做了其他事情。此外,它甚至不看边权重 最后,它完全不是为处理图形表示而设计的。请注意,
start
参数在我假设的字典中用作键,它希望该值是可访问节点的iterable。但你不是在给它一本字典,而是在给它一个列表
对于空列表返回值,如果您这样调用函数:
path = find_all_paths(graph, 'a', 'f')
…那么这是正确的<代码>'a'根本不是图形中的节点。您的节点是元组,以类似'a'
的标识符开始,但也包含一个2元组列表。您每次都必须键入以下内容:
path = find_all_paths(
graph,
start=('a', [('b', 5.0), ('c', 8.0)]),
end=('f', [('d', 2.0), ('g', 7.0)]),
)
恶心
最后,像('d',2.0)
这样的2元组也不是节点。即使您修复了它的其余部分,一旦其中一个参数作为新的start
参数传递到递归函数调用中,这些参数仍然会使if start not in graph:
测试失败。如果您解决了这个问题,它们将与指定的end
节点不匹配。此代码无法执行您想要的操作
我的建议是:
for-edge in-graph['a']:
Edge
的文件,其中包含两个字段:dest
和weight
,您的生活可能会轻松得多。(如果您发现还需要原点,可以填写3个字段:orig
、dest
和weight
)路径
,使用权重
方法。)