CodeBlanks Logo Icon CodeBlanks

Summary - BFS

Run BFS on a graph and print the order in a mini task.

Summary - BFS

BFS is layer-by-layer search using a queue, a visited set and a neighbor loop. It yields the shortest step count.

In this mini task you will run BFS and print the visit order; combine all the pieces.

BFS discovers all reachable vertices in layer order; this is ideal for shortest path.

Practice Print BFS

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

Starter code

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

Sample solution

solution.py
def bfs_print(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_print({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 Summary - BFS: match the terms

Term Meaning
BFS Queue
layer Step
visited No repeat
neighbor Loop

2 Loop condition

Question
while ____:
Answer
while queue:

Explanation: queue is right.

3 What is BFS's time complexity?

  • O(log V)
  • O(V * E)
  • O(V^2)
  • O(V + E) Correct answer

Explanation: O(V + E).

All lessons in Intermediate