簡體   English   中英

用邊指定為元組列表的圖上的 DFS

[英]DFS on a graph specified with edges as list of tuples

我有一個圖,其邊指定為元組列表。 比如說,我們有:

edges = [('human', 'mammal'), ('mammal', 'vertebrate'), ('mouse', 'mammal'), ('vertebrate', 'animal')]

我們如何編寫一個遞歸迭代所有可以從上圖中構造的節點的方法,以在 Python 中執行深度優先搜索遍歷?

任何幫助表示贊賞,謝謝!

這是一個相當有趣的問題,您可能仍然應該嘗試自己解決,但這里有一個實現示例:

from typing import Generator, Union


def construct(edges: list[tuple[str, str]]) -> dict:
    root = {}
    index = {}
    for x, isa in edges:
        if x in root:
            root[isa] = {x: root[x]}
            del root[x]
            index[isa] = root[isa]
        else:
            if x in index:
                raise SyntaxError(f'Invalid tree structure')
            if isa in index:
                index[isa][x] = (d := {})
            else:
                root[isa] = {x: (d := {})}
                index[isa] = root[isa]
            index[x] = d

    return root


def traverse(tree: Union[list[tuple[str, str]], dict]) -> Generator[str, None, None]:
    # this assumes that, if tree is a dict, it is a well-constructed tree, as construct() would return it
    if not isinstance(tree, dict):
        tree = construct(tree)

    for node in tree:
        yield node
        yield from traverse(tree[node])


def main():
    edges = [('human', 'mammal'), ('mammal', 'vertebrate'), ('mouse', 'mammal'), ('vertebrate', 'animal')]
    
    for node in traverse(edges):
        print(node)


if __name__  == '__main__':
    main()

這會在線性時間內構造一棵樹,然后深度優先遍歷它,產生訪問過的節點。 它拒絕具有重復葉或節點值或循環的樹。

輸出:

animal
vertebrate
mammal
human
mouse

我的建議是你試試這個例子,試着理解它,然后用你學到的東西從頭開始編寫你自己的例子。

暫無
暫無

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

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