Data Structures · Visualization
Graph: BFS
Graph
Breadth-First Search explores a graph level by level: it visits all of a node's direct neighbors first, then all of their unvisited neighbors, and so on, spreading outward like ripples in water. Time: O(V + E). Space: O(V) for the queue and visited set.
Big-O: BFS/DFS visit each vertex and edge once: O(V + E).
Graph: BFS
GraphBreadth-First Search explores a graph level by level: it visits all of a node's direct neighbors first, then all of their unvisited neighbors, and so on, spreading outward like ripples in water. It uses a queue to keep track of which nodes to visit next, and a 'visited' set to avoid revisiting nodes and getting stuck in cycles.
How BFS Works
- Start at a chosen node, mark it visited, and add it to a queue.
- While the queue is not empty, remove the front node and process it.
- For each of its neighbors, if not already visited, mark it visited and add it to the back of the queue.
- Repeat until the queue is empty.
BFS Worked Example
Input: BFS from A in graph A-B, A-C, B-D
- Visit A, queue: [B, C]
- Visit B (dequeue), add its unvisited neighbor D → queue: [C, D]
- Visit C (dequeue), no new neighbors → queue: [D]
- Visit D (dequeue) → queue: []
Output: Visit order: A, B, C, D
Press ▶ Run to watch it step by step.
from collections import deque
def bfs(graph, start):
seen = {start}
q = deque([start]) # queue = level order
while q:
v = q.popleft()
print(v, end=" ")
for nxt in graph[v]:
if nxt not in seen:
seen.add(nxt)
q.append(nxt)
# Visits level by level. Finds shortest paths
# in unweighted graphs.
# example: BFS fromBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
BFS Time & Space Complexity
When to Use BFS
- Finding the shortest path in an unweighted graph
- Finding all nodes within a certain number of connections (e.g. '2nd-degree friends')
- Web crawlers exploring pages level by level
- Broadcasting/flood-fill style algorithms
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.