我在代码中实现深度优先搜索时遇到了问题。它只扩展了第一个,然后抛出一个错误(我会在下面的代码之前写出来)。当我放数字而不是字符串时,它可以工作,但我不能让它与字符串一起工作。
Traceback (most recent call last):
File "C:\Users\BAZ\Desktop\GKI\exercise3Code.py", line 45, in <module>
dfs(graph, "HBF", "Zoo/UNI")
File "C:\Users\BAZ\Desktop\GKI\exercise3Code.py", line 28, in dfs
for node in graph[vertex]:
KeyError: 'Schweizerstr.'
import collections
def dfs(graph, root, goal):
seen = set([root])
stack = [root]
while stack:
print("Stack: ", stack)
vertex = stack.pop()
print("Expand: ", vertex)
if vertex == goal:
break
for node in graph[vertex]:
if node not in seen:
seen.add(node)
stack.append(node)
graph = {
"HBF": ["Konig-Heinrich", "Duissern", "Lutherpl"],
"Konig-Heinrich": ["Steinissche G.", "Rathaus"],
"Rathaus": ["Scharnhorststr."],
"Scharnhorststr": ["Kasslerfeldstr."],
"Lutherpl": ["Schweizerstr."],
"Schweizerstr": ["Zoo/UNI"],
"Zoo/UNI": ["Mullheim"],
"Steinissche G.": [], "Kasslerfeldstr": [], "Duissern": [], "Mullheim": []
}
print("DFS")
dfs(graph, "HBF", "Zoo/UNI")
键值不匹配。
...
"Lutherpl": ["Schweizerstr."],
"Schweizerstr": ["Zoo/UNI"],
...
请注意在 "键值 "的末尾有一个句号 "Schweizerstr."
作为 "Lutherpl"
但作为一个键,没有句号 "Schweizerstr"