Maths WorkshopMaths problems with full solutions
Exercise 957Combinatorics › Graph theoryL1Added 3 Nov 2026

BFS and DFS

#BFS#DFS#traversal

Statement

Describe BFS and DFS on a graph.

Hint

BFS uses a queue; DFS uses a stack or recursion.

Show solutionHide solution

Solution

BFS. Start at a root rr. Visit all neighbors of rr, then all unvisited neighbors of those, etc. Uses a queue (FIFO). Computes distances from rr in unweighted graphs.

DFS. Start at rr, recursively explore as deep as possible before backtracking. Uses a stack or recursion. Used for topological sorting, cycle detection, connected components.

Complexity. Both run in O(∣V∣+∣E∣)O(|V|+|E|).

Conclusion. BFS explores level by level; DFS explores depth-first.