'Exception has occurred: KeyError 'h' File "C:\Users\username\Downloads\test.py", line 19, in dfs, how to fix?
# Python dictionary to act as an adjacency list
graph = {
'a' : ['b','c'],
'b': ['d', 'e'],
'd': ['h','i'],
'e': ['j', 'k'],
'c' : ['f','g'],
'g': ['l','m']
}
visited = [] # List of visited nodes of graph.
def dfs(visited, graph, node):
if node not in visited:
visited.append(node)
for neighbor in graph[node]:
dfs(visited, graph, neighbor)
print(node)
# Driver Code
print("Following is the Depth-First Search")
dfs(visited, graph, "a")
print("visited=",visited)
How do I fix this error.
This is a tree. To visualize that you need to know that a has two child b and c.
b has 2 child d and e
d has 2 child h and i
e has 2 child j and k and so on.
I ran a similar code but with numbers in those graph like 7,8 etc instead of a,b,c. It ran perfectly. But here in this case it is not running. Can you debug this
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
