I have written following python program to perform a BFS for the given graph, but after execution it gives the error : Key Error 3. What is wrong in my code?
output=[]
graph = {
1:[2,3,4],
2:[5,6],
5:[9,10],
4:[7,8],
7:[11,12]
}
def bfs(graph,root):
queue = []
visited=set()
queue.append(root)
visited.add(root)
output.append(str(root))
while not(queue==[]):
for item in graph[root]:
if item not in visited:
queue.append(item)
output.append(str(item))
visited.add(item)
root=queue.pop(0)
bfs(graph,1)
print(" ".join(output))