python 求图中所有路径的算法

sc4hvdpw  于 2023-04-10  发布在  Python
关注(0)|答案(2)|浏览(135)

提问

上图是我的一个练习作业的问题陈述。

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或其中的另一个访问过。
如何在允许调用顶点的同时防止循环,只要所述顶点之前没有出现在通向当前顶点的特定路径中?

5cg8jx4n

5cg8jx4n1#

我不确定是否允许使用networkx,但如果允许,您可以使用all_simple_pathsIIUC):
all_simple_paths(G,源,目标,截止值=无)

生成图G中从源到目标的所有简单路径。

#pip install networkx
import networkx as nx

def findAllPaths(vertices, gList, source, destination):
    G = nx.DiGraph()
    G.add_nodes_from(vertices)
    for u in gList:
        for v in gList[u]:
            G.add_edge(u, v)
    
    return list(nx.all_simple_paths(G, source=source, target=destination))

测试/输出(* 基于example *):

all_pp = findAllPaths(
             vertices=[1, 2, 3, 4, 5],
             gList={1: [2, 3], 2: [5], 3: [4], 4: [5], 5: []},
             source=1,
             destination=5)

print(all_pp)
#[[1, 2, 5], [1, 3, 4, 5]]
iezvtpos

iezvtpos2#

要查找图形中两个顶点之间的所有路径,请执行以下操作:

  • 将每条边的成本设置为1。
  • 应用Dijkstra算法寻找顶点间的最便宜路径
  • 路径中链路的增量成本
  • 重复前两步,直到找不到新路径

相关问题