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

时间:2015-12-24 13:54:13

标签: python algorithm python-3.x dictionary

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)

1 个答案:

答案 0 :(得分:0)

如果graph[start]不在字典中,则

start会引发KeyError。您可以将其替换为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