CodeBlanks Logo Icon CodeBlanks

Challenge 3

Run BFS on a graph and print the order.

Challenge 3: BFS

In this challenge you will run BFS on a graph and print the visit order.

Graph: {0: [1, 2], 1: [0, 3], 2: [0, 3], 3: [1, 2]}. Source: 0. Output: [0, 1, 2, 3].

BFS walks layer by layer with a queue and visited set; it gives the shortest step count.

Practice Print BFS

Write bfs_order(graph, start). Print the BFS visit order. Output: [0, 1, 2, 3].

Starter code

solution.py
def bfs_order(graph, start):
    # Print BFS order

Sample solution

solution.py
def bfs_order(graph, start):
    # Print BFS order
    visited = []
    queue = [start]
    while queue:
        node = queue.pop(0)
        if node not in visited:
            visited.append(node)
            for nb in graph[node]:
                if nb not in visited:
                    queue.append(nb)
    print(visited)
bfs_order({0: [1, 2], 1: [0, 3], 2: [0, 3], 3: [1, 2]}, 0)

Expected output

[0, 1, 2, 3]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Challenge 3: match the terms

Term Meaning
BFS Layer
queue Queue
visited No repeat
O(V+E) Fast

2 Which data structure does BFS use?

  • Queue Correct answer
  • Heap
  • Stack
  • Trie

Explanation: Queue.

3 Loop condition

Question
while ____:
Answer
while queue:

Explanation: queue is right.

All lessons in Intermediate