我一直在努力了解深度优先搜索,并在线使用各种来源获得以下代码:
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)