0

enter image description hereI 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))
0

1 Answer 1

2

You're adding nodes to your queue to search from that aren't in graph, and not checking they're in graph before trying to look them up. You can fix this by rewriting your while loop as:

while not(queue==[]):
    for item in graph[root]:
        if item not in visited:
            if item in graph:
                queue.append(item)
            output.append(str(item))
            visited.add(item)
    root=queue.pop(0)

(Alternatively, you could pre-populate graph with all of the unused keys from 1-12 with an empty list as the value.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.