提问
上图是我的一个练习作业的问题陈述。
For the above problem, this was the idea I came up w/ for my recursive algorithm
Base case = you've hit a node u with no outgoing edges. `return [u]`
If there are outgoing edges from current node u to vertices v;
src_paths = []
for each v
child_paths = recursivealgorithm(v)
for each child_path in child_paths:
src_path = [u] + child_path
src_paths.append(src_path)
return src_paths
The trouble w/ this idea as defined is that there is no way to stop an infinite loop happening in case of a cycle in the graph. I thought of various ideas to prevent such a loop (such as keeping track of the vertices visited thus far, maintaining a dictionary including the distance of each visited vertex from the original src & somehow using that to tell if there was a cycle, etc.) but they all had the trouble of also causing issues if 2 child_paths ever converged at a vertex (without creating a cycle)
For eg
上面的图片没有循环,但是如果我写这样的东西
if not visited[v]
作为上面显示的主for循环的条件,为了防止递归调用已经访问过的顶点,那么(取决于Python处理递归调用的顺序)顶点2或顶点4将不能对顶点5进行调用,因为5将已经被1或其中的另一个访问过。
如何在允许调用顶点的同时防止循环,只要所述顶点之前没有出现在通向当前顶点的特定路径中?
2条答案
按热度按时间5cg8jx4n1#
我不确定是否允许使用networkx,但如果允许,您可以使用
all_simple_paths
(IIUC):all_simple_paths
(G,源,目标,截止值=无)生成图G中从源到目标的所有简单路径。
测试/输出(* 基于example *):
iezvtpos2#
要查找图形中两个顶点之间的所有路径,请执行以下操作: