Skip to content

BFS vs DFS: choosing a graph traversal

↑

BFS and DFS both explore graph connectivity, but they prioritize different vertices. BFS explores layers using a queue. DFS follows a branch first using a stack or recursive calls. The distinction becomes visible when a graph contains several alternative routes.

ABCDEF

Visited: –

Queue: –

Neighbors are considered alphabetically. DFS pushes them in reverse order so the first alphabetical neighbor is visited next.

Select BFS and step through from A, then reset and choose DFS. The colored nodes are visited nodes, and the frontier shows pending work. The traversal order is deterministic here only because neighbor ordering is explicitly alphabetical. Different graph representations or insertion order can change the order without making the algorithm wrong.

Question BFS DFS
Main data structure FIFO queue LIFO stack / recursion
Exploration priority Smallest edge distance first Deeper branch first
Shortest path by edge count Yes, in unweighted/equal-weight graphs with parent tracking No general guarantee
Time on adjacency lists O(V + E) O(V + E)
Typical auxiliary space O(V) visited + queue O(V) visited + stack
Common applications Unweighted paths, minimum hops, layer discovery Reachability, backtracking, cycles, topological sort

Both can use O(V) memory in the worst case, but the actual frontier shapes differ. On a wide tree, BFS may keep most of one level in memory. Recursive DFS keeps one active path and uses O(h) call-stack memory on a tree, plus any output; in general graphs a visited set takes O(V). Do not claim DFS always uses less memory.

Preorder, inorder and postorder are DFS orders on a binary tree, with different timing for processing the root. Level-order traversal is BFS on a tree. Inorder is not a generic graph search order because general graphs have no inherent left/right child relationship.

BFS minimizes edges traversed in an unweighted graph, not arbitrary total weights. If A-B has cost 100 and A-C-B costs 2, BFS may choose the direct one-edge route even though its cost is much higher. For nonnegative weighted paths, explore Dijkstra; A* adds a heuristic when appropriate.

Exercise: Sketch a graph with two routes from A to D, one with two edges and one with four. Run both traversals manually and record the queue/stack after each step. Can DFS visit D along the longer path first?

References: GeeksforGeeks BFS vs DFS, W3Schools graph traversal.