
I have written following python program to perform a DFS for the given graph, but after execution it gives the error : Key Error 7. What is wrong in my code?
output=[]
graph = {
9:[8,7,6],
8:[5,4],
6:[3,2],
5:[1,0]
}
def dfs(graph,root):
stack=[]
visited=set()
stack.append(root)
output.append(str(root))
visited.add(root)
while not(stack==[]):
for item in graph[root]:
if item not in visited:
stack.append(item)
visited.add(item)
output.append(str(item))
if set(graph[item]).union(visited)==visited:
stack.pop(-1)
root=stack[len(stack)-1]
continue
root=item
dfs(graph,9)
print(" ".join(output))
Still the problem is not solved after adding suggestions given by @amit i have written the following code and it is giving incorrect output, please help!
output=[]
graph = {
1:[2,3],
2:[4,5],
3:[6,7],
4:[],
5:[],
6:[],
7:[]
}
def dfs(graph,root):
stack=[]
visited=set()
stack.append(root)
output.append(str(root))
visited.add(root)
while not(stack==[]):
for item in graph[root]:
if item not in visited:
stack.append(item)
visited.add(item)
output.append(str(item))
if set(graph[item]).union(visited)==visited:
stack.pop(-1)
if not(stack==[]):
root=stack[len(stack)-1]
else:
break
continue
root=item
dfs(graph,1)
print(" ".join(output))