Depth-First Search

How depth-first search visits a graph by following one path to its end before backing up, its recursive and iterative forms, and what interviewers ask.

14 minLesson 3 of 4
On this page
  1. How depth-first search works
  2. The code
  3. Variants
  4. Pitfalls
  5. In the interview
  6. What to practise next

Depth-first search (DFS) is a way to visit every node reachable from a starting node in a graph by following one path as far as it goes and only then backing up to try the next option. It answers questions about reachability and structure, such as whether one node can reach another, how many separate pieces a graph has, and whether it contains a cycle. You reach for it when you need to explore everything, and the order or length of the paths does not matter.

Without a systematic method, a search through a graph either misses nodes or goes around a cycle forever. DFS avoids both by never entering a node twice.

How depth-first search works

DFS is defined recursively. To run DFS on a node, you mark the node as seen, and then for each neighbour that is not yet seen you run DFS on that neighbour completely before you look at the next one. When a node has no unseen neighbours left, its call returns and the search continues from the node that called it. The seen mark is what prevents the search from circling forever in a graph that has cycles. The call stack of recursion remembers the path from the start to the current node, which is how the search knows where to back up to.

The trace below runs DFS from A on the bus map from Graph Basics. Each node lists its neighbours in alphabetical order. The labels show the order in which nodes are visited, and the highlighted edges are the ones the search used to reach a new node for the first time.

DFS from A on the bus mapUse the arrows or ← → keys
dfs(node):  mark node seen  for each neighbour next of node:    if next not seen: dfs(next)  return
  1. call stack
    0A
    A#1BCDEFG

    1Call dfs(A). A is marked as seen and becomes visit number 1.

  2. call stack
    0A
    1B
    A#1B#2CDEFG

    2A's first neighbour, B, has not been seen, so the search goes to B. A waits on the call stack.

  3. call stack
    0A
    1B
    2D
    A#1B#2CD#3EFG

    3B's neighbours are A, which is seen, and D, which is not. The search goes deeper to D.

  4. call stack
    0A
    1B
    2D
    3C
    A#1B#2C#4D#3EFG

    4D's neighbours are B, which is seen, and C, which is not. The search goes to C, even though C is also directly connected to A.

  5. call stack
    0A
    1B
    2D
    3C
    4E
    A#1B#2C#4D#3E#5FG

    5C's neighbours A and D are both seen, so the search goes to E.

  6. call stack
    0A
    1B
    2D
    3C
    4E
    5F
    A#1B#2C#4D#3E#5F#6G

    6E's neighbour C is seen and F is not, so the search goes to F.

  7. call stack
    0A
    1B
    2D
    3C
    4E
    5F
    6G
    A#1B#2C#4D#3E#5F#6G#7

    7F's neighbours D and E are seen, so the search goes to G. The call stack is now 7 calls deep.

  8. call stack
    0A
    1B
    2D
    3C
    4E
    5F
    A#1B#2C#4D#3E#5F#6G#7

    8G's only neighbour, F, is already seen, so dfs(G) returns to F.

  9. call stack
    0A
    1B
    2D
    3C
    4E
    A#1B#2C#4D#3E#5F#6G#7

    9F has no unseen neighbours left, so dfs(F) returns to E.

  10. call stack
    0A
    1B
    2D
    3C
    A#1B#2C#4D#3E#5F#6G#7

    10E has no unseen neighbours left, so dfs(E) returns to C.

  11. call stack
    0A
    1B
    2D
    A#1B#2C#4D#3E#5F#6G#7

    11C has no unseen neighbours left, so dfs(C) returns to D.

  12. call stack
    0A
    1B
    A#1B#2C#4D#3E#5F#6G#7

    12D's last neighbour, F, is already seen, so dfs(D) returns to B.

  13. call stack
    0A
    A#1B#2C#4D#3E#5F#6G#7

    13B has nothing left to try, so dfs(B) returns to A.

  14. call stack
    A#1B#2C#4D#3E#5F#6G#7
    visited
    7

    14A's last neighbour, C, is already seen, so dfs(A) returns and the search ends. Every stop was visited exactly once.

  15. call stack
    A#1B#2C#4D#3E#5F#6G#7
    DFS path to G
    6 edges
    BFS path to G
    4 edges

    15The visit order is A, B, D, C, E, F, G. The path DFS followed to G has 6 edges, while a BFS from A reaches G in 4.

1 / 15

The edges that the search used to discover each node form a tree, called the DFS tree. The figure compares it with the tree that BFS builds on the same graph.

BFS tree from A A B C D E F G DFS tree from A A B C D E F G
The BFS tree and the DFS tree for the same graph, the same start node and the same neighbour order. BFS gives a wide tree of shortest paths, and DFS gives one long chain.

The code

The recursive version is the shortest way to write DFS. It returns the nodes in the order they were visited.

Recursive
// graph: adjacency list, e.g. { A: ["B", "C"], B: ["A", "D"], ... }
function dfs(graph, start) {
  const seen = new Set();
  const order = [];
  function visit(node) {
    seen.add(node);
    order.push(node);
    for (const next of graph[node]) {
      if (!seen.has(next)) visit(next);
    }
  }
  visit(start);
  return order;
}
// dfs(graph, "A") → ["A", "B", "D", "C", "E", "F", "G"]
# graph: adjacency list, e.g. {"A": ["B", "C"], "B": ["A", "D"], ...}
def dfs(graph, start):
    seen = set()
    order = []
 
    def visit(node):
        seen.add(node)
        order.append(node)
        for nxt in graph[node]:
            if nxt not in seen:
                visit(nxt)
 
    visit(start)
    return order
# dfs(graph, "A") → ['A', 'B', 'D', 'C', 'E', 'F', 'G']
ApproachTimeSpaceWhy
Recursive DFSO(V + E)O(V)Each node is visited once and its neighbour list is read once. The seen set and the call stack can each hold up to V nodes.
Iterative DFSO(V + E)O(V + E)A node can be pushed once for every edge that leads to it, so the stack can hold up to E entries.

Variants

Iterative DFS with your own stack

You can replace the call stack with an explicit stack. This is the right choice when the graph is deep enough to overflow the call stack. You pop a node, skip it if it has already been seen, and otherwise mark it, record it and push its unseen neighbours. The neighbours are pushed in reverse order so that the first neighbour is popped first, which gives the same visit order as the recursive version.

The check for seen nodes happens when a node is popped, as well as when it is pushed. A node can be pushed more than once before it is popped, because it may be a neighbour of several nodes that are still on the stack. On the bus map, both A and D push C. The second copy is skipped when it is popped.

Iterative, with your own stack
function dfsIterative(graph, start) {
  const seen = new Set();
  const order = [];
  const stack = [start];
  while (stack.length > 0) {
    const node = stack.pop();
    if (seen.has(node)) continue; // pushed twice, already handled
    seen.add(node);
    order.push(node);
    const nbrs = graph[node];
    for (let i = nbrs.length - 1; i >= 0; i--) {
      if (!seen.has(nbrs[i])) stack.push(nbrs[i]);
    }
  }
  return order;
}
def dfs_iterative(graph, start):
    seen = set()
    order = []
    stack = [start]
    while stack:
        node = stack.pop()
        if node in seen:
            continue  # pushed twice, already handled
        seen.add(node)
        order.append(node)
        for nxt in reversed(graph[node]):
            if nxt not in seen:
                stack.append(nxt)
    return order

Counting connected components and islands in a grid

A connected component is a set of nodes that can all reach each other. To count them, you scan every node, and each node that has not been seen starts a new component. You add one to the count and run DFS from that node, which marks the whole component as seen so that none of its other nodes starts another count.

On a grid, this is the classic "number of islands" problem. Each land cell is a node, and it is connected to the land cells directly above, below, left and right of it. The DFS that marks one island is often called a flood fill, like the paint bucket tool in an image editor. Cells that touch only at a corner are not connected, which is why islands 3 and 4 in the figure are separate.

1 1 2 1 2 3 4 4 0 1 2 3 0 1 2 3 4
A grid with four islands. Islands 3 and 4 touch only at a corner, at (2, 2) and (3, 1), so they count as separate islands.
// grid: array of strings. "#" is land, "." is water.
function countIslands(grid) {
  const rows = grid.length, cols = grid[0].length;
  const seen = grid.map((row) => new Array(row.length).fill(false));
  function fill(r, c) {
    if (r < 0 || r >= rows || c < 0 || c >= cols) return; // off the map
    if (grid[r][c] !== "#" || seen[r][c]) return;         // water, or done
    seen[r][c] = true;
    fill(r - 1, c); fill(r + 1, c); fill(r, c - 1); fill(r, c + 1);
  }
  let islands = 0;
  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      if (grid[r][c] === "#" && !seen[r][c]) {
        islands++;  // a piece nobody has reached yet
        fill(r, c); // mark all of it
      }
    }
  }
  return islands;
}
 
countIslands(["##..#", "#...#", "..#..", "##..."]); // 4
# grid: list of strings. "#" is land, "." is water.
def count_islands(grid):
    rows, cols = len(grid), len(grid[0])
    seen = [[False] * cols for _ in range(rows)]
 
    def fill(r, c):
        if not (0 <= r < rows and 0 <= c < cols):
            return  # off the map
        if grid[r][c] != "#" or seen[r][c]:
            return  # water, or done
        seen[r][c] = True
        fill(r - 1, c); fill(r + 1, c); fill(r, c - 1); fill(r, c + 1)
 
    islands = 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == "#" and not seen[r][c]:
                islands += 1  # a piece nobody has reached yet
                fill(r, c)    # mark all of it
    return islands
 
count_islands(["##..#", "#...#", "..#..", "##..."])  # 4

Every cell is looked at once by the outer loops, and each land cell is filled once, with four neighbour checks, so the time is O(R × C) for a grid of R rows and C columns. The seen array and the recursion take O(R × C) space in the worst case.

Detecting a cycle in a directed graph

In a directed graph, a seen set is not enough to find a cycle, because reaching a node that was seen earlier is normal when two different paths lead to it. A cycle exists only when the search reaches a node that is still on the current path. To tell these cases apart, each node gets one of three states: unvisited, in progress (its call has started but not returned) or done. If an edge leads to an in-progress node, that node is an ancestor of the current one, so the edge closes a cycle.

Cycle in a directed graph
function hasCycle(graph) {
  const state = new Map(); // missing = unvisited, 1 = in progress, 2 = done
  function visit(node) {
    state.set(node, 1);
    for (const next of graph[node]) {
      if (state.get(next) === 1) return true;
      if (!state.has(next) && visit(next)) return true;
    }
    state.set(node, 2);
    return false;
  }
  return Object.keys(graph).some((n) => !state.has(n) && visit(n));
}
def has_cycle(graph):
    state = {}  # missing = unvisited, 1 = in progress, 2 = done
 
    def visit(node):
        state[node] = 1
        for nxt in graph[node]:
            if state.get(nxt) == 1:
                return True
            if nxt not in state and visit(nxt):
                return True
        state[node] = 2
        return False
 
    return any(n not in state and visit(n) for n in graph)

For an undirected graph the rule is different. Every edge looks like a cycle because the neighbour you came from is always seen, so you ignore the parent and report a cycle only when you reach a seen node that is not the parent. In a directed graph, DFS also supports topological sort, which orders the nodes by the moment their calls return.

When DFS is the wrong tool

DFS does not find shortest paths. It follows whatever route its neighbour order produces, and on the bus map it reached G after 6 edges when 4 were enough. For the fewest edges, use BFS, and for the lowest total weight on a weighted graph, use Dijkstra's algorithm.

Pitfalls

In the interview

Signals that a problem needs DFS include a grid or a graph where you must find connected regions, count groups, or fill an area. Others are questions about whether a path or a cycle exists, problems that ask you to try every route and keep the ones that work (which is backtracking), and anything that describes tasks with prerequisites. Problems about a tree usually also use DFS, because a tree is a graph with no cycles, so no seen set is needed. If the statement says "minimum number of steps" or "shortest", the signal points to BFS instead.

These are the follow-up questions interviewers commonly ask.

What happens if the input is huge or deeply nested?

Recursive DFS can overflow the call stack, because its depth can be as large as the longest path. The usual answer is to switch to an explicit stack, which is limited only by memory.

How do you find the shortest path with DFS?

You do not, in the general case. DFS can be made to try every path and keep the shortest, but that takes exponential time, so the answer is to use BFS for unweighted graphs.

How do you detect a cycle?

In an undirected graph, you report a cycle when you reach a seen node that is not the parent of the current node. In a directed graph, you track which nodes are on the current path and report a cycle when an edge leads back to one of them.

Can you do it without recursion?

Yes. Push the start node on a stack, then repeatedly pop a node, skip it if it has been seen, mark it, and push its unseen neighbours.

What is the time complexity, and does it depend on how the graph is stored?

With an adjacency list, DFS takes O(V + E) time, because each node is entered once and each node's neighbour list is read once. With an adjacency matrix, finding the neighbours of a node means scanning a whole row of V entries, so the total becomes O(V²). On a sparse graph that is much slower, so say which representation you are assuming.

How do you return the path, not only whether one exists?

Keep a map from each node to the node it was reached from, and set it when the search first enters a node. When the target is reached, follow the map backwards to the start and reverse the result. The path is valid but not necessarily the shortest.

Quick check

Graph: { P: [Q, R], Q: [P, S], R: [P, S, T], S: [Q, R], T: [R] }. In what order does recursive DFS from P visit the nodes?

How many islands are in the grid ["#.#", ".#.", "#.#"]?

Why does iterative DFS check seen after popping a node, when it already checked before pushing it?

A directed graph has edges A to B, A to C and B to C. Does recursive DFS from A that only checks a seen set find a cycle?

What to practise next

Read Topological Sort, which orders tasks by the moment each DFS call returns.