On this page · Explore One Distance Layer at a Time
Breadth-first Search
Explore reachable graph nodes in nondecreasing edge distance using a FIFO queue. Fix each distance on first discovery, separate level widths from newly appended children, and account for a wide frontier.
Recognize it when Every move has the same unit cost and the question asks for fewest moves.
Checking your account…
Breadth-first Search Code Labs
Explore One Distance Layer at a Time
Breadth-first search processes all states at distance (d) before any state at distance (d + 1). In an unweighted graph, the first discovery therefore gives a shortest edge distance.
Own the Queue Frontier
The queue contains discovered nodes whose outgoing edges are not fully processed. Capturing the queue length before a level loop isolates one layer even as children are appended behind it.
Trace BFS Layers
Reference
from collections import deque
def bfs_layers(adjacency, start):
if start == -1: return []
queue = deque([start])
seen = {start}
layers = []
while queue:
layer = []
for _ in range(len(queue)):
node = queue.popleft()
layer.append(node)
for neighbor in adjacency[node]:
if neighbor not in seen:
seen.add(neighbor)
queue.append(neighbor)
layers.append(layer)
return layers
Practice
Implement bfs_layers(adjacency, start). Return reachable node indexes grouped by unweighted distance, preserving neighbor order. Use adjacency lists whose neighbor indices are valid vertices; start must be a valid vertex index or the explicit -1 no-source sentinel.
Public tests
Separate queue layers
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
Trace BFS Layers
from collections import deque
def bfs_layers(adjacency, start):
if start == -1: return []
queue = deque([start])
seen = {start}
layers = []
while queue:
layer = []
for _ in range(len(queue)):
node = queue.popleft()
layer.append(node)
for neighbor in adjacency[node]:
if neighbor not in seen:
seen.add(neighbor)
queue.append(neighbor)
layers.append(layer)
return layers
Freeze a Layer While Discovering the Next
The existing layer Lab has two parents of node 3 and one disconnected node. Predict the queue size before each outer iteration; it is not the number of elements after children are appended.
Step
Executed statement
State
Why
Start
queue = deque([start]); seen = {start}; layers = []
queue=[0], seen={0}, layers=[]
Only the source is at distance zero.
Reset root layer
layer = []
layer=[]; queue=[0]
Each outer iteration starts a new result list before capturing its current queue width.
Capture root width
for _ in range(len(queue)):
one loop iteration fixed before enqueuing children
The range is evaluated before the loop starts, so appended children wait for the next outer iteration.
after final outer iteration: layers=[[0], [1, 2], [3]]
Node 4 is disconnected and never belongs to a reachable layer.
Print
Output
print(bfs_layers([[1, 2], [3], [3], [], []], 0))
[[0], [1, 2], [3]]
The distance Lab stores -1 for unreachable nodes. Keeping that sentinel separate from valid distance zero prevents empty or disconnected states from masquerading as a source.
Mark Visited on Enqueue
Mark a node when it enters the queue, not when it leaves. That prevents two parents in the same layer from enqueueing the same neighbor and keeps both work and memory bounded by vertices plus edges.
Find Unweighted Distances
Reference
from collections import deque
def shortest_distances(adjacency, start):
distances = [-1] * len(adjacency)
if start == -1: return distances
distances[start] = 0
queue = deque([start])
while queue:
node = queue.popleft()
for neighbor in adjacency[node]:
if distances[neighbor] == -1:
distances[neighbor] = distances[node] + 1
queue.append(neighbor)
return distances
Practice
Implement shortest_distances(adjacency, start). Return a list of shortest edge distances, using -1 for unreachable nodes. Use adjacency lists whose neighbor indices are valid vertices; start must be a valid vertex index or the explicit -1 no-source sentinel.
Public tests
Assign first-discovery distance
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
Find Unweighted Distances
from collections import deque
def shortest_distances(adjacency, start):
distances = [-1] * len(adjacency)
if start == -1: return distances
distances[start] = 0
queue = deque([start])
while queue:
node = queue.popleft()
for neighbor in adjacency[node]:
if distances[neighbor] == -1:
distances[neighbor] = distances[node] + 1
queue.append(neighbor)
return distances
Choose BFS or DFS
Choose BFS for shortest unweighted paths, minimum moves, or explicit level order. Choose DFS when branch completion, postorder aggregation, or lower frontier width matters. Both traverse reachable graphs in O(V + E); BFS may hold an entire wide layer.
Explain It in an Interview
Say: “The queue is ordered by distance. I mark on enqueue, so each node enters once, and first discovery fixes its shortest unweighted distance.” Mention disconnected nodes and multi-source initialization. Binary Tree Level Order(opens in a new tab) applies the same layer boundary to a tree.
Templates To Memorize
Learn this shape by heart; most problems in this family change only one or two lines of it.
Tree level-order BFS
Freeze the level size, then pop that many.
You need to process a tree level by level.
Trigger words
level order
level by level
right side view
zigzag
minimum depth
serialize tree
from collections import deque
def level_order(root):
if root is None:
return []
levels = []
queue = deque([root])
while queue:
level = []
for _ in range(len(queue)): # exactly the nodes of this level
node = queue.popleft()
level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
levels.append(level)
return levels
Spot it when
'Level order', 'right side view', 'zigzag'.
Minimum depth.
Remember
len(queue) at the start of the while body is the size of the current level.
Use deque.popleft(); list.pop(0) is O(n).
How problems bend it
Right side view: Keep only the last value of each level.
Zigzag order: Reverse every other level before adding it.
BFS shortest path
Mark on enqueue; each level is one step.
Every move costs the same and you want the fewest moves, or several sources spread at the same speed.
Trigger words
minimum steps
fewest moves
minimum minutes
unweighted shortest path
rotting
spreads every minute
word ladder
from collections import deque
def shortest_steps(graph, start, goal):
queue = deque([start])
visited = {start}
steps = 0
while queue:
for _ in range(len(queue)): # every node at distance `steps`
node = queue.popleft()
if node == goal:
return steps
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
steps += 1
return -1
Spot it when
'Minimum number of steps/moves/minutes'.
Unweighted graph or grid.
Rotting oranges, walls and gates.
Remember
The first time BFS reaches a node is along a shortest path.
Several starting points? Put all of them in the queue before the loop (multi-source BFS).
How problems bend it
Rotting oranges: Start with every rotten orange in the queue; each ring is one minute.
Word ladder: Neighbors are the words that differ by one letter.
Python Version Note
Python 3.11+
The code uses standard Python syntax and containers supported by the browser Judge. The Breadth-first Search proof does not depend on a minor Python release.