Python Algorithms
Breadth-First Search (BFS) in Python
Explore a graph level by level with a queue, and find the shortest path in an unweighted graph.
What you'll learn
- Representing a graph as a dict of lists
- Using a deque as the queue
- Tracking visited nodes
BFS from A
Alevel 0Blevel 1Dlevel 2
Clevel 1Elevel 2
Nearest nodes first
Breadth-first search explores every immediate neighbor before moving to the next level and finds shortest paths in unweighted graphs.
Key points
- Start with the source in the queue and in visited.
- Take a node from the front, then add its unvisited neighbours to the back.
- Nodes come out in order of distance from the start.
- Each node and edge is processed once:
O(V + E).
When should you use it?
- Practice problem solving and data structures.
- Process data when every algorithm step must be explicit.
- Prepare for programming exercises, exams, and interviews.
Breadth-First Search in Python visualizer
O(V + E)Use Play or Step to follow each comparison and data movement.
Example code
main.py
from collections import deque
graph = {"A": ["B", "C"], "B": ["D"], "C": ["E"], "D": [], "E": []}
queue = deque(["A"])
visited = {"A"}
order = []
while queue:
node = queue.popleft()
order.append(node)
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
print(order)
Result of running the code
['A', 'B', 'C', 'D', 'E']
Code explanation
The queue stores nodes waiting to be explored, and the visited set prevents cycles. Complexity is O(V + E).
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Try empty, single-item, and duplicate-value inputs.
- Print state after every step to observe the algorithm.
- Benchmark 100, 1,000, and 10,000 items, then compare another approach.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Can We Split Into Two Teams? Decide whether people can be assigned to two teams so that each listed pair is on opposite teams. Medium
- Tree Diameter A tree is a connected undirected graph with no cycles. Medium
- Count Islands Count groups of connected land cells in a grid. Medium