简体   繁体   中英

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." as a value of "Lutherpl" , but as a key there is no period "Schweizerstr"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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