Back to blog
Graph traversal algorithms cover: BFS, DFS, and how to choose
Coding Patterns

Graph Traversal Algorithms: BFS, DFS, and How to Choose

Aug 6, 2026 8 min read Avinash Tyagi
graph traversal algorithms graph traversal breadth first search depth first search bfs vs dfs graph algorithms coding interview data structures dfs bfs

Most graph problems reduce to one question: how do you visit every node without getting lost, stuck in a cycle, or doing exponential work? That is what graph traversal algorithms answer. Breadth-first search and depth-first search are the two engines underneath almost every graph problem you will meet in an interview or in production, from finding the shortest route on a map to detecting a deadlock in a scheduler.

This guide compares the core graph traversal algorithms side by side: how they work, what they cost, and the decision rules that tell you which one to reach for. If you have ever picked BFS when DFS was the cleaner choice (or watched a recursive traversal blow the stack), the goal here is to make that choice deterministic.

What graph traversal actually means

A graph is a set of nodes connected by edges. Traversal is the process of starting at one node and systematically visiting others by following edges. The two things that make graph traversal harder than walking a tree are cycles and multiple paths. A tree has exactly one path between any two nodes and no cycles, so you never revisit anything. A general graph can loop back on itself, so every traversal algorithm needs a visited set to avoid infinite work.

Both breadth-first search and depth-first search visit every reachable node exactly once. The difference is the order in which they do it, and that order is what makes each one suited to different problems.

Breadth-first search: level by level

Breadth-first search explores the graph in rings. It visits the start node, then all of its neighbors, then all of their neighbors, and so on. It uses a queue to remember which nodes to visit next, which enforces first-in, first-out order and keeps the traversal expanding outward evenly.

bfs.pypython
from collections import deque

def bfs(graph, start):
    visited = {start}
    queue = deque([start])
    order = []
    while queue:
        node = queue.popleft()
        order.append(node)
        for neighbor in graph[node]:
            if neighbor not in visited:
                visited.add(neighbor)
                queue.append(neighbor)
    return order

The property that makes BFS special: on an unweighted graph, the first time you reach a node is always along a shortest path measured in number of edges. That single guarantee is why BFS is the default tool for shortest-path questions, level-order problems, and anything where closest first matters.

Depth-first search: follow one path to the end

Depth-first search does the opposite. It picks a neighbor, follows that branch as far as it can go, and only backtracks when it hits a dead end. It uses a stack, either explicitly or through the call stack of a recursive function.

dfs.pypython
def dfs(graph, start, visited=None, order=None):
    if visited is None:
        visited, order = set(), []
    visited.add(start)
    order.append(start)
    for neighbor in graph[start]:
        if neighbor not in visited:
            dfs(graph, neighbor, visited, order)
    return order

DFS is the natural fit whenever the structure of a path matters more than its length: detecting cycles, producing a topological ordering, finding connected components, or exploring every possibility in a backtracking search. Its recursive form is short and readable, which is a real advantage under interview pressure.

Comparing the two algorithms

Both algorithms share the same asymptotic cost, but they trade off memory and behavior in ways that decide which one you want. The diagram below shows how each one visits the same graph in a different order.

  • Data structure: BFS uses a queue (FIFO); DFS uses a stack or recursion (LIFO).
  • Time complexity: both run in O(V + E).
  • Space complexity: BFS uses O(V) up to the widest level; DFS uses O(V) up to the deepest path.
  • Shortest path on unweighted graphs: BFS yes, DFS no.
  • Natural fit: BFS for levels and nearest-first; DFS for cycles, ordering, and backtracking.
  • Risk on huge inputs: a wide BFS frontier eats memory; deep DFS recursion overflows the stack.
BFS versus DFS on the same graph showing different node visit order
BFS and DFS visit the same six-node graph in a different order: BFS level by level, DFS one branch at a time.

Here V is the number of vertices and E the number of edges. Both traversals touch every node and every edge once, so both run in linear time relative to the size of the graph. The memory story is where they diverge. BFS holds an entire level in the queue at once, so a wide, bushy graph can make its frontier enormous. DFS holds a single path, so a long, chain-like graph can push recursion past the stack limit. On deep graphs, an iterative DFS with an explicit stack sidesteps that risk.

The variants that show up most often

Plain BFS and DFS are the foundation, but real problems usually call for a small twist on one of them. Recognizing the variant is half the battle.

Multi-source BFS starts the queue with several nodes at once instead of one, which computes the shortest distance from the nearest of many origins in a single pass. It is the right tool for problems like how far is every cell from the closest gate. We cover the stateful and bidirectional forms in depth in our guide to advanced BFS patterns.

Grid traversal is graph traversal in disguise: each cell is a node and adjacent cells are neighbors. Flood fill, island counting, and shortest-path-in-a-maze problems are all BFS or DFS over an implicit grid graph, as we break down in matrix problems in disguise.

When edges carry weights, plain BFS no longer finds the shortest path, because fewest edges and lowest cost stop agreeing. That is where Dijkstra's algorithm and, for a threshold twist, BFS combined with binary search take over.

A decision framework you can apply under pressure

When you see a graph problem, work through four questions in order.

  1. Is the graph weighted? If yes, BFS and DFS alone will not give shortest paths; you need Dijkstra, Bellman-Ford, or a specialized approach. If no, continue.
  2. Do you need the shortest path or the nearest something? If yes, use BFS and rely on its level-order guarantee. Record the distance as you enqueue each node.
  3. Do you need ordering, cycle detection, or exhaustive exploration? If yes, use DFS. Track discovery and finish times if you need topological order or cycle classification.
  4. Is the graph pathologically deep or wide? A very deep graph argues for iterative DFS to avoid stack overflow; a very wide graph may make BFS memory-heavy, where DFS or iterative deepening can help.

This ladder resolves the large majority of traversal questions without guesswork. For the deeper trade-off between traversal and dynamic programming as ways to explore a search space, see our comparison of BFS, DFS, and DP.

Where traversal meets real systems

These algorithms are not only interview material. Package managers run topological sort (a DFS variant) to order installs. Build systems use the same idea to schedule compilation. Web crawlers are BFS over the link graph. Garbage collectors trace reachable objects with DFS. Social networks compute degrees of separation with BFS. Once you see the queue-versus-stack distinction, you start noticing it everywhere in production code, not just in coding challenges.

Practice with intent

The fastest way to internalize graph traversal algorithms is deliberate practice on problems that force the choice, then reviewing why one algorithm was cleaner than the other. Levelop's interactive system design and coding-pattern lessons at levelop.dev walk through these traversals on real problems, and our full library of pattern breakdowns lives on the Levelop blog. Pattern recognition, not memorization, is what turns a hard graph question into a routine one.

Frequently asked questions

What is graph traversal?

Graph traversal is the process of visiting every reachable node in a graph exactly once by following edges, using a visited set to avoid revisiting nodes and looping forever on cycles. Breadth-first search and depth-first search are the two standard traversal algorithms.

What are the main graph traversal algorithms?

The two core graph traversal algorithms are breadth-first search (BFS), which explores level by level using a queue, and depth-first search (DFS), which follows one path to the end using a stack or recursion. Most other graph algorithms build on one of these two.

When should I use BFS versus DFS?

Use BFS when you need the shortest path in an unweighted graph or anything nearest first, because BFS reaches each node along a minimum-edge path. Use DFS for cycle detection, topological ordering, connected components, and backtracking, where the structure of a path matters more than its length.

What is the time complexity of graph traversal?

Both BFS and DFS run in O(V + E) time, where V is the number of vertices and E the number of edges, because each node and each edge is examined once. They differ mainly in space: BFS uses memory proportional to the widest level, DFS proportional to the deepest path.

Does BFS work on weighted graphs?

Plain BFS does not find shortest paths on weighted graphs, because fewest edges and lowest total weight no longer coincide. For weighted graphs, use Dijkstra's algorithm, or BFS with a threshold-and-binary-search technique when the constraint is a maximum edge weight rather than a sum.

References

Cormen, Leiserson, Rivest, and Stein, Introduction to Algorithms (MIT Press), chapters on elementary graph algorithms.

CP-Algorithms: Breadth-first search

CP-Algorithms: Depth-first search

Wikipedia: Graph traversal

Keep reading

Coding Patterns

BFS vs DFS vs DP: When to Use Which to Explore a Search Space

BFS, DFS, and DP are three ways to explore a search space, not three unrelated topics. Here is a two-minute decision for which to use on any interview problem.

Read article
Coding Patterns

Advanced BFS: Multi-Source, Stateful, and Bidirectional

Plain BFS is only the warm-up. Here are the three variations interviews actually test: multi source BFS, stateful BFS, and bidirectional BFS, with Python and a decision guide.

Read article
Coding Patterns

BFS + Binary Search: the Shortest Path When a Threshold, not Distance, Matters

Plain BFS finds the fewest steps, but some path problems minimize the largest jump instead. Here is how BFS plus binary search on the answer solves them, with a Python template.

Read article