Skip to content
Concept ยท Data Structures and Algorithms

BFS vs DFS: Differences, Python Code and a Decision Table

Younus FardeenBy Younus FardeenUpdated 1 Dec 20269 min read
Short answer

BFS (breadth first search) visits nodes level by level using a queue, so it finds the fewest-edge path in an unweighted graph. DFS (depth first search) follows one branch as far as it goes before backing up, using a stack or recursion. Both take O(V + E) time. Use BFS for shortest paths, DFS for cycles and components.

On this pageBFS vs DFS in one tableThe three implementations, traced on one graphShortest path in an unweighted graph: why BFS winsGrid problems: counting islands with DFS and BFSHow to decide: a checklist and a tableFrequently asked questions

This page is for students who can already read an adjacency list and now need to choose between BFS and DFS under interview or exam pressure. The basics of graphs, adjacency lists and the two traversals are on the graph data structure page; here the focus is the difference, with one graph traced by hand and by code.

Every code block below was run with Python 3 on 1 December 2026 and the output shown is the real output. Complexity figures are the standard textbook results, so they do not change with time.

  1. 1Pick the questionShortest path, or explore all?
  2. 2Shortest in edgesUse BFS and a queue
  3. 3Explore, cycle, componentUse DFS and a stack
  4. 4Check the limitsDepth, width, weights
  5. 5Weighted edgesMove to Dijkstra
How to choose between BFS and DFS.

BFS vs DFS in one table

Both algorithms visit every node reachable from a start node exactly once. They differ in which waiting node they pick next. BFS takes the oldest one (a queue, first in first out). DFS takes the newest one (a stack, last in first out, or the call stack when written recursively).

BFSDFS
Data structureQueue (collections.deque)Stack (a list) or recursion
Visit orderStart, then all neighbours, then neighbours of neighboursStart, then one neighbour, then its neighbour, to a dead end, then back up
TimeO(V + E)O(V + E)
Extra spaceO(V), at worst the widest levelO(V), at worst the deepest path
Shortest path (unweighted)Yes, fewest edgesNo guarantee
Cycle detection, components, topological orderPossible, less naturalThe usual choice
Risk in PythonLarge queue on wide graphsRecursionError on deep graphs if recursive

V is the number of nodes (vertices) and E the number of edges. With an adjacency list each node's neighbour list is read once, which gives O(V + E). With an adjacency matrix both become O(V squared), because every row is scanned.

The three implementations, traced on one graph

The graph has six nodes and these directed edges: A to B and C, B to D and E, C to F, E to F. D and F have no outgoing edges. The code stores it as a dictionary of lists, builds BFS with a deque, and writes DFS twice: once with an explicit stack and once with recursion.

from collections import deque

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

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

def dfs_iterative(graph, start):
    seen = set()
    stack = [start]
    order = []
    while stack:
        node = stack.pop()
        if node in seen:
            continue
        seen.add(node)
        order.append(node)
        for nxt in reversed(graph[node]):
            stack.append(nxt)
    return order

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

print("BFS          :", bfs(graph, "A"))
print("DFS iterative:", dfs_iterative(graph, "A"))
print("DFS recursive:", dfs_recursive(graph, "A"))

BFS prints A, B, C, D, E, F. It finishes level one (B and C) before touching level two (D, E and F). Both DFS versions print A, B, D, E, F, C: they go A, B, D, hit a dead end, back up to B, take E, reach F, and only then return to C.

Two details trip people up. First, mark a node as seen when you add it to the BFS queue, not when you remove it, or the same node can be queued many times. Second, the iterative DFS pushes neighbours in reversed order so that the first neighbour is popped first and the output matches the recursive version. Without reversed it still visits every node, just in a different valid order.

Which DFS to write

Write the recursive one when the structure is shallow or when you are explaining your idea; it reads like the definition. Switch to the explicit stack when depth can reach tens of thousands, because CPython's default recursion limit is 1000 frames (see the sys module docs). The recursion page explains why each call takes a stack frame.

Shortest path in an unweighted graph: why BFS wins

BFS visits nodes in order of distance from the start: all nodes one edge away, then all nodes two edges away. The first time it reaches the goal, no shorter route can exist. To recover the route, store each node's parent when you first see it, then walk back from the goal.

from collections import deque

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

def shortest_path(graph, start, goal):
    parent = {start: None}
    queue = deque([start])
    while queue:
        node = queue.popleft()
        if node == goal:
            path = []
            while node is not None:
                path.append(node)
                node = parent[node]
            return path[::-1]
        for nxt in graph[node]:
            if nxt not in parent:
                parent[nxt] = node
                queue.append(nxt)
    return None

path = shortest_path(graph, "A", "F")
print(path, "edges:", len(path) - 1)
print(shortest_path(graph, "D", "A"))

The route from A to F is A, C, F, two edges. D to A prints None because the edges are directed and no route leads back. DFS would happily return A, B, E, F (three edges) first, since it commits to the first branch it tries.

This only holds when every edge costs the same. Once edges have different costs, BFS counts hops, not total cost, and you need Dijkstra's algorithm. If the weights are only 0 and 1, a deque-based variant still works, but that is rare in interviews.

Grid problems: counting islands with DFS and BFS

A grid is a graph in disguise: each cell is a node and its up, down, left and right cells are neighbours. You never build the adjacency list; you compute neighbours from coordinates. The classic problem is LeetCode 200, Number of Islands: count the groups of connected land cells (marked 1) in a grid.

from collections import deque

grid = [
    "11000",
    "11000",
    "00100",
    "00011",
]

def count_islands_dfs(grid):
    rows, cols = len(grid), len(grid[0])
    seen = set()

    def dfs(r, c):
        if not (0 <= r < rows and 0 <= c < cols):
            return
        if grid[r][c] == "0" or (r, c) in seen:
            return
        seen.add((r, c))
        for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
            dfs(r + dr, c + dc)

    count = 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == "1" and (r, c) not in seen:
                count += 1
                dfs(r, c)
    return count

def count_islands_bfs(grid):
    rows, cols = len(grid), len(grid[0])
    seen = set()
    count = 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == "1" and (r, c) not in seen:
                count += 1
                seen.add((r, c))
                queue = deque([(r, c)])
                while queue:
                    x, y = queue.popleft()
                    for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                        nx, ny = x + dx, y + dy
                        if 0 <= nx < rows and 0 <= ny < cols and grid[nx][ny] == "1" and (nx, ny) not in seen:
                            seen.add((nx, ny))
                            queue.append((nx, ny))
    return count

print(count_islands_dfs(grid), count_islands_bfs(grid))

The 4 by 5 grid has three islands: the 2 by 2 block at top left, the single cell in the middle, and the pair at bottom right. The program prints 3 3, one count from each traversal. The outer double loop finds an unseen land cell, adds one to the count, and the traversal then marks the whole island as seen so it is never counted twice.

On a grid, DFS and BFS give the same answer for this problem, so choose on safety: a recursive DFS on a 1000 by 1000 grid can go a million frames deep and crash, while BFS keeps a bounded queue. For shortest path in a maze or the time for rotting oranges to spread (LeetCode 994), BFS is the correct tool because it advances one step at a time in all directions.

How to decide: a checklist and a table

  1. Does the question ask for the minimum number of steps, moves or edges? Use BFS.
  2. Does it ask whether something is reachable, or to visit or count everything? Either works; pick DFS if recursion is shallow, BFS if not.
  3. Does it involve cycles, connected components, topological order, or exploring all paths (backtracking)? Use DFS.
  4. Are edges weighted? Neither is enough alone; read the Dijkstra page.
  5. Is the graph very deep or very wide? Deep means avoid recursive DFS; wide means BFS queue memory grows.
Problem typeBetter choiceReason
Fewest moves in a maze or word ladderBFSLevels are distances
Number of islands, connected componentsDFS or BFSOnly need to mark everything reachable
Detect a cycle in a directed graphDFSTrack nodes on the current path
Course schedule, build orderDFS (or BFS with in-degrees)Topological ordering
Generate all paths, permutations, puzzlesDFSBacktracking is DFS with undo
Spread over time (rotting oranges, fire)BFS from all sources at onceEach queue round is one time step
Shortest path with different costsDijkstraBFS ignores weights

For more graph problems by application, see applications of graphs. For interview frequency of these questions, the DSA interview questions page lists where graphs sit among other topics.

Frequently asked questions

What is the main difference between BFS and DFS?

BFS explores a graph level by level using a queue, so it reaches near nodes first. DFS follows one path as deep as possible using a stack or recursion, then backs up. Both run in O(V + E). The practical difference is that BFS gives fewest-edge paths in unweighted graphs and DFS suits cycle checks, components and exhaustive search.

Which is faster, BFS or DFS?

Neither is faster in the worst case: both are O(V + E) on an adjacency list. In practice the winner depends on the question. If you stop as soon as you find a target, BFS is quicker when the target is near the start and DFS can be quicker when it lies deep down the first branch you try.

Why does BFS find the shortest path and DFS does not?

BFS visits every node at distance k before any node at distance k + 1, so the first time it reaches a node, it used the fewest edges. DFS commits to the first branch it tries and may reach the goal by a long detour before checking shorter branches. This is true only when all edges have equal cost.

Can BFS and DFS be used on trees?

Yes. A tree is a graph with no cycles, so you need no seen set if you only move from parent to child. BFS on a tree is level-order traversal. DFS on a tree is pre-order, in-order or post-order, depending on when you process the node relative to its children.

Should I use recursion or a stack for DFS in Python?

Use recursion for clarity when depth is small. Use an explicit stack when depth could pass a few hundred to a thousand, since CPython's default recursion limit is 1000 frames and a deeper recursive DFS raises RecursionError. Raising the limit with sys.setrecursionlimit is possible but can crash the interpreter on very deep input.

Is DFS or BFS better for the number of islands problem?

Either gives the correct count, since you only need to mark each connected region once. BFS or an explicit-stack DFS is safer on large grids because a recursive DFS can go as deep as the number of cells in one island. For small interview grids, recursive DFS is the shortest code to write.

Learn this with mentors

Programmes for builders and engineers with admissions open: live classes, mentors and project work.

Continue learning

Concept

Graph data structure

Vertices, edges, BFS, DFS and cycle checks with tested code

8 min read
Concept

Dijkstra's algorithm

heapq code, a traced example, negative weights and BFS, Bellman-Ford compared

7 min read
Explainer

What is recursion?

Base case, call stack and examples, with code in three languages.

5 min read