Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Exploring Level by Level

from collections import deque

graph = {
    "A": ["B", "C", "D"],
    "B": ["E", "F"],
    "C": ["G"],
    "D": ["H"],
    "E": [],
    "F": [],
    "G": [],
    "H": [],
}
queue = deque(["A"])
visited = []

while queue:
    node = queue.popleft()
    if node not in visited:
        visited.append(node)
        queue.extend(graph[node])

print(visited)
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']

Breadth-first search explores a graph one layer at a time

The graph overview explained who is connected to whom. BFS turns that structure into a strategy: start from one node, visit its immediate neighbors first, then expand outward level by level using a queue.

Core Explanation

BFS visits nearby nodes before moving deeper. It is useful when shortest path by number of edges matters or when level-based exploration is important.

Read the figure without code
  • the node labels show one valid BFS visitation order

  • the blue start node is visited first

  • the green nodes are all reached in one edge from A

  • the yellow nodes are reached only after the first layer is finished

That is the key BFS promise: finish the current distance layer before moving farther away.

Continuity from the graph overview

The graph notebook introduced adjacency lists. BFS is the first algorithm that systematically consumes those neighbor lists to explore the network.

Worked Example and Practice Lab

Iterative BFS with an explicit queue

Expected output
Iterative BFS order: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']

This version makes the queue visible in code, which is why it is often the clearest first implementation.

Recursive BFS using a queue helper

Expected output
Recursive BFS order: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']

Reading BFS behavior

These short prompts focus on what the queue and visitation order mean.

  1. Explain why BFS uses a queue instead of a stack.

  2. Describe what “level by level” means in your own words.

  3. Give one reason BFS is useful for shortest-hop problems in unweighted graphs.

  4. Explain how BFS differs from a depth-first approach.

Hint

Think about what should happen first: the oldest discovered node or the most recently discovered node.

Guided Practice

StackStacks are more associated with depth-first behavior.
QueueCorrect. BFS explores level by level using a queue.
TupleA tuple is not the traversal driver here.
Set onlyA visited set can help, but the core traversal structure is a queue.

Which nodes belong to the first BFS layer after the start node in the figure?

E, F, and GThose are reached only after the first layer is complete.
B, C, and DCorrect. Those are the direct neighbors of A, so BFS reaches them before the outer layer.
A and BA is the start node, not part of the next layer.
G and H onlyThose nodes are deeper than one edge away.

Key Takeaway

BFS explores a graph in expanding layers, which makes it a natural fit for shortest-hop reasoning and level-based discovery. DFS will keep the same graph idea but switch the exploration rhythm completely.