Abbildung: DFS

def dfs(graph, node):
    stack = []  #  python list模拟栈,先进后出
    visited = set()
    stack.append(node)
    visited.add(node)
    while len(stack):
        # 弹出最近入栈的结点
        cur_node = stack.pop()
        if cur_node in graph.keys():
            neighbor_nodes = graph[cur_node]

            for next in neighbor_nodes:
                if next not in visited:
                    stack.append(next)
                    visited.add(next)
        print(cur_node)


graph = {
    "A": ["B", "C"],
    "B": ["C", "D"],
    "C": ["E", "F"]
}
dfs(graph, "A")

Guess you like

Origin blog.csdn.net/zmj1582188592/article/details/121765293
dfs