Video in progress
How do BFS and DFS differ, and which do you choose depending on the problem?
BFS goes layer by layer with a queue and gives the shortest path in an unweighted graph. DFS goes as deep as it can in one direction with a stack or recursion, and suits connectivity, cycles, topological order and counting all paths. Both are O(V + E).
📖 Answer
A simple rule for choosing:
| What you need | Choice |
|---|---|
| the path with the fewest steps (unweighted) | BFS |
| nodes exactly k steps from the starting point | BFS |
| walking through every connected part | either |
| cycle detection, topological sort | DFS |
| enumerating all options, backtracking | DFS |
There is a difference in memory too. BFS keeps a whole layer in the queue, which in a wide tree can be a lot. DFS keeps the current path, whose size is the depth. But recursive DFS throws a StackOverflowError on a deep graph, and then you write it iteratively with an ArrayDeque.
static List<Integer> bfsOrder(Map<Integer, List<Integer>> g, int start) {
List<Integer> order = new ArrayList<>();
Set<Integer> visited = new HashSet<>(List.of(start));
Deque<Integer> q = new ArrayDeque<>(List.of(start));
while (!q.isEmpty()) {
int v = q.poll();
order.add(v);
for (int u : g.getOrDefault(v, List.of())) {
if (visited.add(u)) q.offer(u); // we mark it when adding to the queue
}
}
return order;
}
One subtle point: in BFS, mark a node visited when you put it into the queue, not when you take it out. Otherwise the same node gets into the queue several times.
Sign up to mark studied questions and save your progress.