#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Home / Blog /

Advantages and Disadvantages of BFS and DFS

Mastering Graph Traversal Algorithms in AI

Published
6 min read
Scroll Down

Advantages and disadvantages of BFS and DFS: the short answer

Breadth First Search (BFS) and Depth First Search (DFS) are uninformed search strategies: they explore a state space without any estimate of how far the goal is. How each one works, with traces and code, is covered in BFS and DFS in AI. This page is about the trade-offs: what each one is good at, where each one breaks, and what to use instead.

Advantages of BFS

  • Complete: if a solution exists and every node has a finite number of successors, BFS will find it.
  • Finds the shallowest solution: when there is more than one solution, BFS returns the one with the fewest steps. This makes it optimal when every step has the same cost.
  • Cannot get lost down an infinite path, because it never goes deeper than level d+1 before finishing level d.

Disadvantages of BFS

  • High memory use: every node of the current level must be stored to generate the next level. The frontier grows as O(bd).
  • Slow when the solution is deep: it must expand every shallower node first.
  • Not optimal when step costs differ: fewest steps is not the same as lowest cost.

Advantages of DFS

  • Low memory use: it stores only the current path plus the unexplored siblings along it, O(b·m).
  • Can reach a deep solution quickly if it happens to pick the right branch, without generating all the shallow nodes first.
  • Simple to write recursively, and the natural fit for backtracking, cycle detection and topological sorting.

Disadvantages of DFS

  • Not complete: in an infinite or very deep search space, or a graph with cycles and no visited check, it can go down one branch forever.
  • Not optimal: the first solution it finds may be much longer than the best one.
  • States can be revisited many times, and deep recursion can overflow the call stack.
S.No.Breadth First Search (BFS)Depth First Search (DFS)
1Uses a queue (FIFO) as the frontier.Uses a stack (LIFO) or recursion.
2Better when the goal is close to the start, or when you need the fewest steps.Better when solutions are deep and plentiful, or memory is limited.
3Expands all neighbours of a node before going deeper.Follows one neighbour as deep as possible, then backtracks.
4Time O(V + E) on an explicit graph; O(bd) in a search tree.Time O(V + E) on an explicit graph; O(bm) in a search tree.
5Space O(bd).Space O(b·m).
6Complete (finite b); optimal for equal step costs.Not complete in infinite spaces; not optimal.

Here b is the branching factor, d the depth of the shallowest goal, and m the maximum depth of the search tree. This notation follows Russell and Norvig, Artificial Intelligence: A Modern Approach.

The memory difference, measured

"BFS uses more memory" is easy to say. The program below measures it. It searches a complete tree where every node has 3 children (b = 3) and records the largest frontier each algorithm has to hold at any moment.

from collections import deque

def children(node, b, depth):
    # node is a tuple path from the root; leaves are at the given depth
    if len(node) == depth:
        return []
    return [node + (i,) for i in range(b)]

def bfs_peak(b, depth):
    queue, peak, expanded = deque([()]), 1, 0
    while queue:
        node = queue.popleft()
        expanded += 1
        queue.extend(children(node, b, depth))
        peak = max(peak, len(queue))
    return expanded, peak

def dfs_peak(b, depth):
    stack, peak, expanded = [()], 1, 0
    while stack:
        node = stack.pop()
        expanded += 1
        stack.extend(children(node, b, depth))
        peak = max(peak, len(stack))
    return expanded, peak

for depth in (4, 8, 12):
    e1, p1 = bfs_peak(3, depth)
    e2, p2 = dfs_peak(3, depth)
    print(f"depth {depth:2}: nodes {e1:>7} | BFS peak frontier {p1:>6} | DFS peak frontier {p2:>3}")

Output:

depth  4: nodes     121 | BFS peak frontier     81 | DFS peak frontier   9
depth  8: nodes    9841 | BFS peak frontier   6561 | DFS peak frontier  17
depth 12: nodes  797161 | BFS peak frontier 531441 | DFS peak frontier  25

Both algorithms expand the same number of nodes when they search the whole tree, but BFS has to hold an entire level at once (312 = 531,441 nodes at depth 12), while DFS holds at most (b − 1)·d + 1 = 25. Doubling the depth squares the BFS frontier but only doubles the DFS one.

Scale that up to a more realistic AI problem. With b = 10 and 1,000 bytes per stored node, BFS generates about 1.1 million nodes to reach depth 6 (roughly 1.1 GB), about 111 million for depth 8 (about 111 GB) and about 11 billion for depth 10 (about 11 TB). This is why plain BFS runs out of memory long before it runs out of time on puzzles with deep solutions.

Where each algorithm fails: concrete cases

BFS on a weighted graph

Suppose A connects directly to D with cost 5, and also A → B costs 1 and B → D costs 1. BFS returns A → D because it has one edge, but its cost is 5, while A → B → D costs only 2. BFS minimises the number of steps, not the total cost. Uniform-cost search (Dijkstra's algorithm) is the fix.

DFS in a space with repeated states

In the water jug problem, filling a jug and then emptying it brings you back to the state you started from. A DFS that does not remember visited states can cycle between (0, 0) and (4, 0) forever. With a visited set it terminates on a finite state space, but the path it returns is often longer than necessary.

DFS with an unlucky branch order

If the goal is at depth 2 in the rightmost branch, but the leftmost branch is 1,000 levels deep, DFS explores all 1,000 levels on the left before it looks right. Its running time depends on m (the deepest branch), not d (the shallowest goal), which is why its time bound is O(bm).

BFS when every solution is deep

In an N-Queens or Sudoku search, every solution sits at the bottom of the tree (all queens placed, all cells filled). BFS must build every partial board at every level before it reaches any complete one, which is wasted work. DFS with backtracking reaches complete boards directly.

Fixes that combine the advantages

TechniqueWhat it fixesCost
Visited (closed) setDFS and BFS looping on graphs with cyclesMemory for every visited state
Depth-limited DFSDFS running forever down an infinite branchIncomplete if the goal is deeper than the limit
Iterative deepening DFSGets BFS's completeness and shortest-step answer with DFS's O(b·d) memoryRe-expands shallow levels; for b = 10 only about 11% extra work
Bidirectional BFSBFS's time and memory, by searching from both endsO(bd/2); needs a known goal state and reversible moves
Uniform-cost searchBFS not optimal on weighted edgesPriority queue instead of a plain queue

When a good estimate of distance to the goal is available, informed search goes further: best-first search expands the most promising node first, and the A* algorithm combines path cost with the estimate. Local methods such as hill climbing drop the frontier almost entirely, at the price of completeness.

When to choose BFS and when to choose DFS

  • Choose BFS when you need the fewest moves (shortest path in an unweighted graph, minimum moves in a puzzle), when the goal is likely to be shallow, and when the level width fits in memory.
  • Choose DFS when memory is tight, when any solution will do and solutions are deep (backtracking puzzles), or when the task is structural: detecting cycles, topological ordering, finding connected or strongly connected components.
  • Choose iterative deepening when the depth of the solution is unknown and you want BFS's completeness and shortest-step answers without its memory cost.

For implementation details of each algorithm on its own, see breadth first search explained and depth first search with code and use cases. Search strategies are part of the problem-solving module in Uncodemy's Artificial Intelligence course.