我的图表如下:
g = {1: [2, 4], 2: [1, 3, 5], 3: [2], 4: [1, 5, 7], 5: [2, 4, 6], 6: [5, 8], 7: [4]}
我使用DFS算法来探索图g
:
def paths(g,start,path = []):
path = path + [start]
for edge in g[start]:
if edge not in path:
path = paths(graph, edge, path)
return path
这里我只获得算法探索的节点列表。例如,如果start
节点为1,那么我得到:
[1,2,3,5,4,7,6,8]
如何从起始节点获取所有路径?让我们说起始节点是1,然后我想得到:
[[1,2,3],[1,2,5,6,8],[1,4,5,6,8],[1,4,7]]