簡體   English   中英

在python中編寫更好的遞歸深度優先搜索

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

我正在嘗試在python中構建一個圖形庫(以及標准的圖形算法)。 我試圖實現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)

這工作正常,但我不滿意它是如何使用的。 例如,目前你需要這樣做

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

而不是這個,我想以這種方式使用DFS

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

使用遞歸DFS,我無法提出像上面那樣工作的實現。 有人可以給我一些指示,我該如何實現這一目標?

只需創建一個調用您已有的方法的包裝器方法:

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

這里DFS2是您在上面顯示的方法。

實際上你為什么不設置path默認為空列表? 所以使用相同的代碼但略有不同的參數:

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

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

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

您可以使用chutsu建議的訪問節點的空默認值,但要小心使用可變的默認參數 此外,我建議使用集合而不是列表進行常量查找。

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