简体   繁体   English

试图在Python中使用DFS递归查找图中的所有路径

[英]trying to find all the path in a graph using DFS recursive in Python

I have found a solution that was posted some times ago and I have tried to apply it to my exercise but it doesn't work. 我找到了一个很久以前发布的解决方案,我试图将它应用到我的练习中,但它不起作用。 I have a class graph that has nodes and edges and a method childrenOf that gives all the children of a node. 我有一个包含节点和边的类图,以及一个给出节点所有子节点的方法childrenOf。 All this works fine. 这一切都很好。 This is my code for the DFS search and I want to find all the paths: 这是我的DFS搜索代码,我想找到所有路径:

def myDFS(graph,start,end,path=[]):
path=path+[start]
if start==end:
    return path
paths=[]
for node in graph.childrenOf(start):
    if node not in path:
        paths.extend(myDFS(graph,node,end,path))            
return paths

I only got empty lists. 我只有空列表。 WHere do I need to look at? 我需要看一下吗? When I was doing path=myDFS... in the loop I had at least the last path. 当我在循环中做path = myDFS ...时,我至少有了最后一条路径。 I tried path+=myDFS without success. 我尝试了路径+ = myDFS但没有成功。 The graph was created with success so it doesn't come from it. 图表是成功创建的,因此它不是来自它。 Thanks 谢谢

Since you only want to get all paths from start to end, the path is appended to your total path list when it reaches the end. 由于您只想从头到尾获取所有路径,因此路径在到达末尾时会附加到总路径列表中。 The total list of paths is not returned but rather populated: 路径的总列表不会返回,而是填充:

paths = []

def myDFS(graph,start,end,path=[]): 
    path=path+[start] 
    if start==end:
        paths.append(path) 
    for node in graph.childrenOf(start):
        if node not in path:
            myDFS(graph,node,end,path)

i've flattened JSON of nested dicts (depth was four) 我已经将嵌套dicts的JSON弄平了(深度为4)

{'output':
    'lev1_key1': 'v11',
    'lev1_key2': {
       {'lev2_key1': 'v21',
        'lev2_key2': 'v22',
       }
 }

with recursive call of 用递归调用

paths = []
_PATH_SEPARATOR = '/'
def flatten(treeroot, path=''):
  path=path
  if isinstance(treeroot, dict):
    for k in treeroot.keys():
        s_path = path + _PATH_SEPARATOR + str(k)
        flatten(treeroot[k], path=s_path)
  elif isinstance(treeroot, str):
     path = path + _PATH_SEPARATOR + treeroot
     paths.append(path)
  elif isinstance(treeroot, list):
    # if node has more than one child 
    for k in treeroot.keys():
        s_path = path + _PATH_SEPARATOR + str(k)
        flatten(k, path=s_path)

result is 结果是

{
 'output/lev1_key1': 'v11',
 'output/lev1_key2/lev2_key1': 'v21',
 'output/lev1_key2/lev2_key2': 'v22',
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM