如何解决dfs,bfs中的KeyError



我试图使用以下python代码创建bfs、dfs程序。不幸的是,出现了这个错误。。。。。。任何人请帮我

Traceback(最后一次调用(:文件";D: \1260.py";,第35行,in打印(dfs(图,1((文件";D: \1260.py";,第30行,dfsstack.extend(图[节点](KeyError:4

graph = {
1: [2, 3, 4],
2: [4],
3: [4]
}
def bfs(graph, start_node):
visit = list()
queue = list()
queue.append(start_node)
while queue:
node = queue.pop(0)
if node not in visit:
visit.append(node)
queue.extend(graph[node])

return visit
def dfs(graph, start_node):
visit = list()
stack = list()
stack.append(start_node)
while stack:
node = stack.pop()
if node not in visit:
visit.append(node)
stack.extend(graph[node])
return visit
if '__main__' == __name__:
print(dfs(graph, 1))
print(bfs(graph, 1))
stack.extend(graph[node])

graph中没有node密钥。

try:
stack.extend(graph[node])
except KeyError:
print(f"Unexpected node: {node}")

最新更新