BFS vs DFS
BFS vs DFS compared — data structure, shortest paths, memory and use cases, with interactive visualizers for both.
Breadth-first search (BFS) explores a graph level by level with a queue; depth-first search (DFS) dives down one branch with a stack (or recursion). Both visit every node in O(V + E) but suit different problems.
BFS vs DFS at a glance
| BFS | DFS | |
|---|---|---|
| Data structure | Queue (FIFO) | Stack / recursion |
| Shortest path (unweighted) | Yes | No |
| Memory | Wide frontier | Path depth |
| Best for | Shortest paths, levels | Cycles, topological sort, mazes |
When to use BFS
Use BFS for shortest paths on unweighted graphs and level-order traversal.
When to use DFS
Use DFS for cycle detection, topological sorting, and exploring all paths.
Tools for BFS & DFS
Breadth-First Search (BFS) Visualizer
Interactive breadth-first search on a grid — draw walls, move start/goal, generate mazes, step through the level-by-level expansion. Runs in your browser.
Open toolDepth-First Search (DFS) Visualizer
Interactive depth-first search on a grid — draw walls, move start/goal, generate mazes, step through the deep-dive exploration. Runs in your browser.
Open toolDijkstra's Algorithm Visualizer
Interactive Dijkstra pathfinding on a grid — draw walls, move start/goal, generate mazes, step through the search. Runs in your browser.
Open toolMaze Generator
Animated maze generator using recursive division — step through the wall carving, adjust speed, regenerate. Pairs with the pathfinding visualizers. Runs in your browser.
Open toolBFS vs DFS
Which is better, BFS or DFS?
Neither — they fit different jobs. BFS finds the shortest path on unweighted graphs and explores by level; DFS is better for cycle detection, topological sort and backtracking. Both run in O(V + E).