gpt4 book ai didi

python - python 中的 dfs 不工作请指导我有关错误

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:20:17 24 4
gpt4 key购买 nike

def dfs(graph, start, visited=None):

if visited is None:
visited = set()
if start in visited:
return
visited.add(start)
for a in graph[start]:
if a not in visited:
dfs(graph, a, visited)
return visited
graph={'A':['B'],'B':['C']}

b=dfs(graph,'A')

print(b)

最佳答案

graph[start] 将提高 KeyError如果 start 不在字典中。您可以将其替换为 dict.get返回默认值(空序列):

def dfs(graph, start, visited=None):
if visited is None:
visited = set()
if start in visited:
return
visited.add(start)
for a in graph.get(start, []): # <---
if a not in visited:
dfs(graph, a, visited)
return visited

关于python - python 中的 dfs 不工作请指导我有关错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34453876/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com