Skip to content

BFS vs DFS: Differences, Code and When to Use Each

Quick answer

BFS uses a queue and goes level by level. DFS goes deep first. See a hand trace, runnable Python and a rule for choosing between them.

BFS vs DFS: Differences, Code and When to Use Each

BFS (breadth-first search) explores a graph level by level using a queue, while DFS (depth-first search) follows one path as deep as it can before backing up, usually using recursion or a stack. Use BFS to find the path with the fewest edges. Use DFS for cycles, components and exhaustive exploration.

Key takeaways

  • BFS uses a queue and visits vertices in order of distance, in edges, from the start.
  • DFS uses recursion or a stack and goes deep before it goes wide.
  • For an unweighted graph, BFS finds a path with the fewest edges. DFS does not promise that.
  • Princeton's Algorithms companion says BFS takes time proportional to V + E in the worst case, and DFS time proportional to the sum of degrees of the vertices it reaches.

On this page:

PointBFSDFS
Order of visitingNeighbours first, level by levelOne branch to its end, then back
Helper structureQueueRecursion or a stack
Fewest edges from the sourceYes, in an unweighted graphNot guaranteed
Running time (Princeton)Proportional to V + E in the worst caseProportional to the sum of degrees of vertices reached
Typical usesShortest path in edges, level-order problemsCycle detection, connected components, maze-style search

What are BFS and DFS?

Both are ways of visiting every vertex reachable from a starting vertex in a graph, each exactly once. They differ only in which unvisited vertex they take next.

The Princeton Algorithms companion site (Sedgewick and Wayne) calls depth-first search a classic recursive method for systematically examining each of the vertices and edges in a graph. For BFS it says breadth-first search is a classic method for finding a shortest path, meaning one with a minimal number of edges, and that it maintains a queue of vertices that have been marked but whose adjacency lists have not been checked.

The NIST Dictionary of Algorithms and Data Structures agrees in short form. Its depth-first search entry (modified 15 October 2021) defines DFS as any search algorithm that considers outgoing edges (children) of a vertex before any of the vertex's siblings, and notes that it is easily implemented with recursion. Its breadth-first search entry (modified 22 April 2019) defines BFS as any search algorithm that considers neighbours of a vertex before any outgoing edges of that vertex, and says it is typically implemented with a queue.

An analogy: BFS checks a building one floor at a time. DFS follows one corridor to its end before returning to try another.

How do BFS and DFS differ on the same graph?

Take a hand-worked graph with vertices A to E and edges A-B, A-C, B-D and C-E, starting at A, with neighbours taken in alphabetical order.

  1. BFS: visit A. Queue B and C. Visit B, queue D. Visit C, queue E. Visit D, then E. Order: A, B, C, D, E.
  2. DFS: visit A, go to B, go deeper to D. D has no new neighbours, so back up to A, then go to C and E. Order: A, B, D, C, E.

Same graph, same start, different order. For a made-up map of six cities where each edge is one road segment, BFS from Delhi gives the route with the fewest road segments to every other city. DFS would also reach them, but not necessarily by the shortest route.

What does the code look like?

This Python runs as written and reproduces the trace above. BFS uses collections.deque as the queue, DFS uses recursion, and the third function counts the fewest edges between two vertices.

from collections import deque

graph = {
    "A": ["B", "C"],
    "B": ["A", "D"],
    "C": ["A", "E"],
    "D": ["B"],
    "E": ["C"],
}

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

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

def shortest_edges(graph, start, goal):
    dist = {start: 0}
    queue = deque([start])
    while queue:
        node = queue.popleft()
        if node == goal:
            return dist[node]
        for nxt in graph[node]:
            if nxt not in dist:
                dist[nxt] = dist[node] + 1
                queue.append(nxt)
    return None

print("BFS:", bfs(graph, "A"))                # ['A', 'B', 'C', 'D', 'E']
print("DFS:", dfs(graph, "A"))                # ['A', 'B', 'D', 'C', 'E']
print("Edges A to E:", shortest_edges(graph, "A", "E"))  # 2

The only structural difference between the two traversals is the queue versus the call stack. Replace the queue with a stack and the same loop goes deep first, although the exact visiting order can differ from the recursive version.

When should you use BFS and when DFS?

Choose BFS when distance in edges matters. Choose DFS when you need to explore everything along a path, or track the path you took.

  • Shortest path with equal edge costs: BFS. Princeton states that for any vertex reachable from the source, BFS computes a shortest path, and that no path from the source to that vertex has fewer edges. This is for unweighted graphs, so weighted routes need other algorithms.
  • Level-order problems, such as degrees of connection: BFS.
  • Cycle detection and connected components: DFS is the usual choice.
  • Maze-style search that goes deep first: DFS.

To build the groundwork, read the graph data structure explained, queues, stacks and how recursion works.

How fast are BFS and DFS?

Both are linear in the size of the graph. Princeton says BFS takes time proportional to V + E in the worst case, where V is the number of vertices and E the number of edges. For DFS it says the time to mark all vertices connected to a source is proportional to the sum of their degrees.

So neither wins on speed. The choice is about the problem, not performance. We do not quote space figures here because the pages we relied on do not state them.

What mistakes do beginners make?

  • Forgetting the visited set. On a graph with cycles, the search loops forever. Mark a vertex when you first see it.
  • Marking too late in BFS. If you mark a vertex only when you pop it, the same vertex can enter the queue several times. The code above marks on insertion.
  • Assuming DFS finds shortest paths. It finds a path, not necessarily the shortest.
  • Using BFS on weighted graphs for cheapest routes. BFS counts edges, not costs.
  • Deep recursion. A very long path can exceed Python's recursion limit. An explicit stack avoids this.

Next step: run the code, change the graph by adding the edge D-E, and predict both orders before you run it again. For related practice, see applications of the graph data structure and data structures and algorithms explained.

Frequently asked questions

What is the main difference between BFS and DFS?

BFS explores level by level using a queue. DFS goes as deep as possible along one path first, using recursion or a stack.

Which finds the shortest path, BFS or DFS?

BFS, in an unweighted graph. Princeton states that BFS computes a path from the source with the fewest edges. DFS does not guarantee the shortest path.

What data structure does BFS use?

A queue. NIST says BFS is typically implemented with a queue, and Princeton describes a queue of marked vertices whose adjacency lists are unchecked.

What is the time complexity of BFS and DFS?

Princeton says BFS takes time proportional to V + E in the worst case, and DFS time proportional to the sum of the degrees of the vertices it reaches.

When should I use DFS instead of BFS?

Use DFS for cycle detection, connected components and maze-style searches that go deep. Use BFS when you need the fewest edges.

Share LinkedIn X WhatsApp
×

Our Courses

Practice-Based Learning Tracks, Supercharged By A.I.