小编Hel*_*444的帖子

加法和+ =给出不同的列表结果(深度优先搜索)

我一直在努力了解深度优先搜索,并在线使用各种来源获得以下代码:

graph = {'A': ['B', 'D'], 'B': ['E'], 'C': [], 'D': ['C', 'E'], 
         'E': ['H', 'I', 'J'], 'F': [], 'G': [], 'H': ['F'], 
         'I': [], 'J': ['G']}

def dfs(graph, start, end, path=None):
    if path == None:
        path = []
    path = path + [start]
    paths = []
    if start == end:
        return [path]
    for neighbour in graph[start]:
        if neighbour not in path:
            paths.extend(dfs(graph, neighbour, end, path))
    return paths

print(dfs(graph, 'A', 'G'))
Run Code Online (Sandbox Code Playgroud)

这会输出所需的结果:

[['A', 'B', 'E', 'J', 'G'], ['A', 'D', 'E', …
Run Code Online (Sandbox Code Playgroud)

python list depth-first-search

4
推荐指数
1
解决办法
47
查看次数

标签 统计

depth-first-search ×1

list ×1

python ×1