Skip to main content

Differences between DFS and BFS

Short answer

DFS uses a stack (or recursion), going deep before backtracking; BFS uses a queue, visiting level by level. DFS memory is O(depth), BFS O(width). BFS finds shortest paths in unweighted graphs; DFS does not guarantee that.

What are the differences between DFS and BFS?

PointDFS (depth first)BFS (breadth first)
Data structureStack (or recursion)Queue
OrderGoes deep along a path, then backtracksVisits level by level
MemoryO(depth) of the path in a treeO(width), can be large (all vertices of a level)
Shortest pathDoes not guarantee itFinds shortest path in an unweighted graph
TimeO(V + E) with listsO(V + E) with lists
ApplicationsCycle detection, topological sort, connected components, maze solvingShortest path, level-order, nearest neighbours, web crawling
CompletenessMay go very deep (infinite path problem)Finds a solution at the shallowest level
ImplementationSimple with recursionNeeds explicit queue

Example: for the tree A-(B, C), B-(D, E), BFS gives A B C D E, DFS gives A B D E C.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Data Structure and Algorithm chapter 10 questions →