Data structures

Graph Traversal: BFS & DFS

Run BFS and DFS on the same graph. Watch the queue and stack change the order in which nodes are discovered.

5 minLevel 2/3The interactive stage stays ad-free.
Visited0 / 11AlgorithmBFSOrder—
012345678910

BFS explores level by level and is the basis for shortest paths in unweighted graphs. DFS dives deep and is used for connectivity, cycles, and backtracking. Cyan edges are the traversal tree.

What you are seeing

1

BFS uses a queue: it visits all neighbors at the current distance before going deeper.

2

DFS uses a stack or recursion: it follows one path as deep as possible before backtracking.

3

The cyan edges show the traversal tree — the parent relationship discovered by the algorithm.

Why it matters

BFS and DFS are the base for pathfinding, cycle detection, topological sorting, web crawling, and social-network analysis.

Complexity & details

Time: O(V + E). Space: O(V) for the queue, stack, and visited set.

Frequently asked questions

When should I use BFS instead of DFS?+

Use BFS for shortest paths in unweighted graphs and level-order exploration. Use DFS for connectivity, cycles, backtracking, and topological order.

Why must we mark nodes as visited?+

Graphs can contain cycles. Without a visited set, traversal could loop forever or process the same node repeatedly.