在图形Python中查找所有路径
我有一些图的邻接矩阵。我不知道这个图是什么样子,它取决于起始条件。它可以是定向的,也可以是无向的,循环的,等等。 所以,我需要找到所有顶点之间的所有路径 例如,在这个特殊的图中,我们有在图形Python中查找所有路径,python,algorithm,graph,Python,Algorithm,Graph,我有一些图的邻接矩阵。我不知道这个图是什么样子,它取决于起始条件。它可以是定向的,也可以是无向的,循环的,等等。 所以,我需要找到所有顶点之间的所有路径 例如,在这个特殊的图中,我们有 2 0 3 2 1 3 2 0 1 3 0 2 1 3 0 1 3 1 3 我知道DFS或BFS,但不知道如何在此任务中实现它们。假设您已将此图的邻接矩阵定义为 adj_matrix = [[0, 1, 1, 1], [0, 0, 0, 1], [1,
2 0 3
2 1 3
2 0 1 3
0 2 1 3
0 1 3
1 3
我知道DFS或BFS,但不知道如何在此任务中实现它们。假设您已将此图的邻接矩阵定义为
adj_matrix = [[0, 1, 1, 1],
[0, 0, 0, 1],
[1, 1, 0, 0],
[0, 0, 0, 0]]
在这种情况下,对每个路径进行递归深度优先搜索的方式如下:
def iter_paths(adj, min_length=2, path=None):
# different paths for starting and recurring
# you could use two different methods, the first calling the second and
# the second calling itself, if you wanted
if not path:
for start_node in range(len(adj)):
yield from iter_paths(adj, min_length, [start_node])
else:
# yield a path as soon as we first encounter it
if len(path) >= min_length:
yield path
# if we encounter a cycle (current location has been visited before)
# then don't continue to recur
if path[-1] in path[:-1]:
return
# search for all paths forward from the current node, recursively
current_node = path[-1]
for next_node in range(len(adj[current_node])):
if adj[current_node][next_node] == 1:
yield from iter_paths(adj, min_length, path + [next_node])
print(list(iter_paths(adj_matrix)))
这将生成以下路径列表:
[[0, 1],
[0, 1, 3],
[0, 2],
[0, 2, 0],
[0, 2, 1],
[0, 2, 1, 3],
[0, 3],
[1, 3],
[2, 0],
[2, 0, 1],
[2, 0, 1, 3],
[2, 0, 2],
[2, 0, 3],
[2, 1],
[2, 1, 3]]
广度优先算法与深度优先算法非常相似——不同的是,它不使用递归,而是保留已访问的
path
s的运行列表,当深度优先算法调用自身时,广度优先算法只需将新路径添加到列表中。它将在while
循环中迭代,直到到达该列表的末尾,然后返回完整列表
这只会改变我们检查节点的顺序,在本例中,您会注意到深度优先搜索会按“字母顺序”排列节点,而广度优先搜索会按长度的升序排列节点。如果您有
13
,为什么其他所有顶点都没有呢,你的问题是什么?图形算法已经研究了很长时间了。我建议您通过谷歌搜索“graph finding all paths”或类似的搜索方式在线查找内容,这将帮助您了解如何解决此问题。我无法准确找到代码中的错误位置,但我的编译器(VS 2019)和在线编译器得到相同的错误递归错误:相比之下,超过了最大递归深度。此错误发生在示例中使用的矩阵上。其他矩阵也有同样的误差。另外,代码的最后一行缺少一个右括号“)”@OlehChaika已修复,抱歉。忘记将minu length
传递到递归调用中。如果愿意,请再试一次,现在应该可以了。