简体   繁体   English

在python中编写更好的递归深度优先搜索

[英]Writing a better recursive depth-first search in python

I'm trying to build a graph library in python (along with standard graph-algorithms). 我正在尝试在python中构建一个图形库(以及标准的图形算法)。 I've tried to implement DFS and this is what it looks like 我试图实现DFS,这就是它的样子

def DFS(gr, s, path):
    """ Depth first search 
    Returns a list of nodes "findable" from s """
    if s in path: return False
    path.append(s)
    for each in gr.neighbors(s):
        if each not in path:
            DFS(gr, each, path)

This is working fine but I'm not happy with how it needs to be used. 这工作正常,但我不满意它是如何使用的。 Eg currently you need to do this 例如,目前你需要这样做

 path = []
 DFS(mygraph, "s", path)
 print path

Instead of this, I want to DFS to be used in this manner 而不是这个,我想以这种方式使用DFS

path = DFS(mygraph, "s")
print path

With the recursive DFS, I am unable to come up with the implementation that works like above. 使用递归DFS,我无法提出像上面那样工作的实现。 Can someone give me some pointers on how can I achieve this? 有人可以给我一些指示,我该如何实现这一目标?

Just make a wrapper method that calls the one you already have: 只需创建一个调用您已有的方法的包装器方法:

def DFS(gr, s):
    path = []
    DFS2(gr, s, path)
    return path

Here DFS2 is the method you showed above. 这里DFS2是您在上面显示的方法。

Actually why don't you just set path to have a default of an empty list? 实际上你为什么不设置path默认为空列表? So using your same code but slightly different arguments: 所以使用相同的代码但略有不同的参数:

# Original
def DFS(gr, s, path):

# Modified
def DFS(gr, s, path=[]):

# From here you can do
DFS(gr, s)

You can use an empty default value for the visited nodes, as suggested by chutsu, but be careful with using mutable default arguments . 您可以使用chutsu建议的访问节点的空默认值,但要小心使用可变的默认参数 Also I would suggest using a set instead of a list for constant lookup. 此外,我建议使用集合而不是列表进行常量查找。

def DFS(gr, s, visited=None):
    """ Depth first search 
    Returns a list of nodes "findable" from s """
    if visited == None:
        visited = set([s])

    for each in gr.neighbors(s):
        if each not in visited:
            visited.add(each)
            DFS(gr, each, visited)

    return visited

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

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