Algorithms · Visualized
Breadth-First Search
Graph Algorithms
Traverse, order, and find shortest paths and spanning trees on graphs — the machinery behind maps, networks, schedulers and dependency resolvers.
BFS explores a graph level by level: it visits every node reachable in 1 step from the start, then every node reachable in 2 steps, and so on, using a FIFO queue to remember the frontier. Time: O(V + E) average, O(V + E) worst; space: O(V) for the queue, visited set and distances.
Big-O: Traversals O(V + E); Dijkstra O(E log V) with a heap; Bellman–Ford O(V·E); Floyd–Warshall O(V³); MST O(E log E).
Breadth-First Search (BFS)
Graph AlgorithmsBFS explores a graph level by level: it visits every node reachable in 1 step from the start, then every node reachable in 2 steps, and so on, using a FIFO queue to remember the frontier. Because it reaches each node the first time via a fewest-edges path, BFS naturally computes shortest hop-counts (and shortest paths in unweighted graphs).
How Breadth-First Search Works
- Mark the start node visited, record its distance as 0, and enqueue it.
- Dequeue the front node u and append it to the visit order.
- Scan u's neighbours; for every unvisited neighbour v, mark it visited, set dist[v] = dist[u] + 1, and enqueue it.
- Repeat until the queue is empty — every reachable node has then been processed exactly once.
- Anything still unvisited at the end belongs to a different connected component.
Breadth-First Search Worked Example
Input: {graph: A—B, A—C, B—C, B—D, C—D, C—E, D—E, D—F, E—F, start: A}
A(0) enqueued. Dequeue A → discover B(1), C(1). Dequeue B → C seen, discover D(2). Dequeue C → D seen, discover E(2). Dequeue D → discover F(3). Dequeue E, F — nothing new. Order: A B C D E F; the distances are exactly the hop-counts.
from collections import deque
def bfs(graph, start):
visited = [False] * len(graph)
dist = {start: 0}
q = deque([start])
order = []
while q:
u = q.popleft()
order.append(u)
for v in graph[u]:
if not visited[v] and v not in dist:
visited[v] = True
dist[v] = dist[u] + 1
q.append(v)
return order, distBehind 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.
Breadth-First Search Time & Space Complexity
When to Use Breadth-First Search
- Shortest path in unweighted graphs — maze escape, fewest-clicks navigation, word ladders.
- Level-order analysis: social-network degrees of separation, web crawling by depth, peer-to-peer lookup.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.