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 . Visit all neighbors of , then all unvisited neighbors of those, etc. Uses a queue (FIFO). Computes distances from in unweighted graphs.
DFS. Start at , 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 .
Conclusion. BFS explores level by level; DFS explores depth-first.