简体   繁体   English

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

[英]How do I implement DFS in the code below?

I'm having a problem implementing Depth-First-Search in my code.我在代码中实现深度优先搜索时遇到问题。 It only expands the first one and then throws an error (I'll write it below before the code).它只会扩展第一个然后抛出错误(我会在代码之前写在下面)。 It works when I put numbers instead of strings, but I can't get it to work with strings.当我输入数字而不是字符串时它可以工作,但我不能让它与字符串一起工作。

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")

The keys/values don't match up:键/值不匹配:

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

Notice there is a period at the end of "Schweizerstr."请注意, "Schweizerstr." as a value of "Lutherpl" , but as a key there is no period "Schweizerstr"作为"Lutherpl"的值,但作为键没有句点"Schweizerstr"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM