簡體   English   中英

如何有效地在 Python 中實現遞歸 DFS?

[英]How to implement recursive DFS in Python efficiently?

我正在嘗試在 Python 中實現遞歸 DFS。 我的嘗試是:

def dfs_recursive(graph, vertex, path=[]):
    path += [vertex]

    for neighbor in graph[vertex]:
        # print(neighbor)
        if neighbor not in path:  # inefficient line
            path = dfs_recursive(graph, neighbor, path)

    return path


adjacency_matrix = {"s": ["a", "c", "d"], "c": ["e", "b"],
                    "b": ["d"], "d": ["c"], "e": ["s"], "a": []}

不幸的是, if neighbor not in path ,這條線效率很低,而不是我應該做的。 我希望輸出是按順序訪問的節點,但沒有重復。 所以在這種情況下:

['s', 'a', 'c', 'e', 'b', 'd']

如何有效地輸出以 DFS 順序訪問但沒有重復的節點?

使用dict

def dfs_recursive(graph, vertex, path={}):
    path[vertex] = None

    for neighbor in graph[vertex]:
        if neighbor not in path:
            dfs_recursive(graph, neighbor)

    return path

adjacency_matrix = {"s": ["a", "c", "d"], "c": ["e", "b"],
                    "b": ["d"], "d": ["c"], "e": ["s"], "a": []}

print(*dfs_recursive(adjacency_matrix, "s"))

輸出:

s a c e b d

你可以這樣做:

def dfs_recursive(graph, vertex, dic, path):

    dic[vertex] = 1;
    path += vertex
    for neighbor in graph[vertex]:

        if not neighbor in dic: 
           dfs_recursive(graph, neighbor, dic, path)



graph = {"s": ["a", "c", "d"], "c": ["e", "b"],
                    "b": ["d"], "d": ["c"], "e": ["s"], "a": []}

path = [];
dic = {}
dfs_recursive(graph,"s",dic,path);

print(path)

您需要有一個字典來進行高效查找,如果您想要路徑,您可以將其添加到不同的結構中,如上所示。

您可以將OrderedDict用於path變量。 這將使in運算符在恆定時間內運行。 然后要將其轉換為列表,只需從該字典中獲取鍵,這些鍵保證按插入順序排列。

我也會把整個函數的遞歸部分放到一個單獨的函數中。 這樣你就不必在每個遞歸調用中將path作為參數傳遞:

from collections import OrderedDict

def dfs_recursive(graph, vertex):
    path = OrderedDict()

    def recur(vertex):
        path[vertex] = True
        for neighbor in graph[vertex]:
            if neighbor not in path:
                recur(neighbor)

    recur(vertex)
    return list(path.keys())

adjacency_matrix = {"s": ["a", "c", "d"], "c": ["e", "b"],
                    "b": ["d"], "d": ["c"], "e": ["s"], "a": []}

print(dfs_recursive(adjacency_matrix, "s"))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM