如何在下面的代码中实现DFS?

问题描述 投票:-1回答:1

我在代码中实现深度优先搜索时遇到了问题。它只扩展了第一个,然后抛出一个错误(我会在下面的代码之前写出来)。当我放数字而不是字符串时,它可以工作,但我不能让它与字符串一起工作。

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")
python python-3.x artificial-intelligence depth-first-search breadth-first-search
1个回答
0
投票

键值不匹配。

...
"Lutherpl": ["Schweizerstr."],
"Schweizerstr": ["Zoo/UNI"],
...

请注意在 "键值 "的末尾有一个句号 "Schweizerstr." 作为 "Lutherpl"但作为一个键,没有句号 "Schweizerstr"

© www.soinside.com 2019 - 2024. All rights reserved.