小编Vic*_*cky的帖子

python中的深度优先搜索(DFS)代码

你能告诉我下面DFS代码中的错误吗?它给出了正确的结果AFAIK,但我不知道什么时候会失败.

graph1 = {
    'A' : ['B','S'],
    'B' : ['A'],
    'C' : ['D','E','F','S'],
    'D' : ['C'],
    'E' : ['C','H'],
    'F' : ['C','G'],
    'G' : ['F','S'],
    'H' : ['E','G'],
    'S' : ['A','C','G']
}

visited = []

def dfs(graph,node):
    global visited
    if node not in visited:
        visited.append(node)
        for n in graph[node]:
            dfs(graph,n)

    dfs(graph1,'A')
    print(visited)
Run Code Online (Sandbox Code Playgroud)

输出:

['A', 'B', 'S', 'C', 'D', 'E', 'H', 'G', 'F']
Run Code Online (Sandbox Code Playgroud)

python depth-first-search

3
推荐指数
3
解决办法
5万
查看次数

标签 统计

depth-first-search ×1

python ×1