What is Breadth-First Search?
Graph Algorithms·6 min·Python code
Breadth-First Search (BFS) explores a graph level by level, visiting every neighbour of a node before moving deeper. Queues hold what to visit next and visited sets stop repeats. In unweighted graphs, BFS finds the shortest path between two nodes.
Breadth-First Search Explores in Rings
Drop a stone into a pond. Ripples reach the closest points first, then spread outward in rings. BFS explores a graph the same way. Starting from one node, it visits every node one step away, then every node two steps away, and so on.
BFS never jumps ahead to a distant node while closer ones wait. Fanning out evenly means the first arrival at a node used the fewest possible edges, and that single property makes BFS the natural choice for shortest path questions in unweighted graphs.
BFS Queue and Visited Set
BFS keeps two pieces of state, a queue of nodes waiting for a visit and a set of nodes already seen. Start by adding the source node to the queue and marking it visited. Then loop. Remove the node at the front, check its neighbours and, for every neighbour you have not seen, mark it visited and add it to the back.
Queues enforce level order. Nodes leave in discovery order, so BFS drains one full layer before the next begins. Visited sets matter just as much, since a cycle would send BFS around the same nodes forever.
Mark a node visited when you add it to the queue, not when you remove it. Otherwise duplicates can pile up.
BFS Shortest Path in Unweighted Graphs
Traversal becomes a shortest path search once you remember where every node came from. Keep a parent map. When you discover a neighbour, record the node you reached it from. At the target, follow parent pointers backward to rebuild the route, then reverse it. Edges on that route give the distance from the source.
This works because every edge counts as one step. With weighted edges, a path with more edges can weigh less, so BFS can be wrong. Weighted graphs call for Dijkstra's algorithm, or 0-1 BFS when weights are only 0 and 1.
Practise on CodeStory's Breadth-First Search practice problems. Compare it with Depth-First Search on the same graph.
Breadth-First Search Code Example in Python
from collections import deque
def bfs_shortest_path(graph, start, goal):
"""Return the shortest path (fewest edges) from start to goal."""
queue = deque([start])
parent = {start: None} # doubles as the visited set
while queue:
node = queue.popleft()
if node == goal:
path = []
while node is not None:
path.append(node)
node = parent[node]
return path[::-1] # reverse: start to goal
for neighbor in graph[node]:
if neighbor not in parent: # not yet visited
parent[neighbor] = node
queue.append(neighbor)
return None # goal unreachable
Edit this code in the browser IDE on CodeStory, free on the platform. Open the CodeStory App
Breadth-First Search Time and Space Complexity
| Time | O(V + E) with an adjacency list, and O(V²) with an adjacency matrix |
|---|---|
| Space | O(V) for the queue and the visited set |
V means vertices and E means edges. BFS removes every vertex from the queue once and checks every edge once (twice in undirected graphs), so the cost is O(V + E) in every case.
Watch the Frontier Expand Level by Level
Seeing every ring of nodes join the queue shows why the first arrival is the shortest. Follow either of these on your own input, one step at a time.
When to Use Breadth-First Search
- You need the shortest path or fewest moves in an unweighted graph or grid, like mazes, word ladders and knight moves on a chessboard.
- You count the minimum steps to reach a target state, or list every node within k steps of a source.
- You traverse a tree in level order, or process any graph one layer at a time.
- You test reachability and find connected components, meaning whether two nodes connect at all.
Mistakes to Avoid
- Marking a node visited when you remove it from the queue instead of when you add it. Nodes then enter the queue many times, which wastes work and can corrupt distances.
- Popping from the front of a plain list with list.pop(0). That costs O(n) and quietly pushes the traversal to O(V²), so use collections.deque as your FIFO queue.
- Expecting shortest paths on weighted graphs. BFS counts edges, not total weight, so different edge costs call for Dijkstra's algorithm.
Breadth-First Search FAQs
Is breadth-first search hard to learn?
No. Loops here are short, and expanding outward in rings is intuitive, especially when you watch it animate step by step. People trip on using a proper queue and on the moment to mark nodes visited. Several practice problems build muscle memory.
When should I use BFS instead of DFS?
Choose BFS for the shortest path or fewest steps in an unweighted graph, or to process nodes in order of distance from the source. Choose DFS for exhaustive exploration, cycle detection or topological sorting. BFS holds a full frontier at once, so it uses more memory.
What is the time complexity of breadth-first search?
O(V + E) with an adjacency list, since every node leaves the queue once and every edge gets checked once. Space is O(V) for the queue and the visited set. With an adjacency matrix the time becomes O(V²).
Does BFS always find the shortest path?
Yes in unweighted graphs, where every edge counts as one step, because the first arrival at a node used the fewest edges. No in weighted graphs, since a route with more edges can weigh less. Use Dijkstra's algorithm there.
Why does BFS use a queue?
Queues are first in, first out, so nodes leave in discovery order. That order finishes one layer before the next starts, which keeps distances correct.
How does BFS rebuild the shortest path?
BFS stores a parent for every node it discovers. At the target, you follow parents back to the source and reverse the list. Code above does exactly that.
How do I practise breadth-first search on CodeStory?
Watch the frontier grow in the visualisers, write the queue loop yourself, then try CodeStory's Breadth-First Search practice problems.
Related Guides
Guides are step one. In a CodeStory batch you code BFS yourself, then explain every queue step in a scored mock round.
Talk to a Mentor