Skip to content

What is Depth-First Search?

Graph Algorithms·6 min·Python code

Depth-First Search (DFS) explores as far as possible along one branch before backtracking. From a start node, it visits an unvisited neighbour, then that node's neighbour, and so on, using recursion or an explicit stack and marking visited nodes to avoid cycles.

Depth-First Search Goes Deep Then Backtracks

Picture exploring a maze by always taking the first unexplored corridor. You retreat only at a dead end. That is depth-first search. Instead of fanning out evenly, DFS follows one path as deep as it goes, then retreats to the last junction with an untried option and dives again.

Go deep, backtrack, repeat. That single habit makes DFS natural to write with recursion, because every call is one step deeper and every return is one step back. Watching it animate edge by edge makes the structure clear.

DFS With Recursion, a Stack and Visited State

DFS needs a way to reach neighbours, a way to remember where it has been and a way to backtrack. Visit a node, mark it visited, then recurse into every unvisited neighbour. Call stacks remember and backtrack for you.

Swap recursion for an explicit stack and you get the iterative version. Push the start node, then repeatedly pop, visit and push unvisited neighbours.

Visited sets are not optional on graphs. Any cycle sends DFS into an infinite loop without one, and shared nodes get explored again and again. Trees have no cycles, so remembering the parent is enough there. Neighbour order decides which branch goes first, so DFS output is not unique until you fix that order.

Cycle Detection, Components and Topological Sort

Backtracking exposes useful facts almost for free. Track which nodes sit on the recursion stack, and meeting one that is still in progress reveals a cycle. Start DFS from every unvisited node and count the fresh starts to get the number of connected components.

Topological sort falls out of the same traversal. Record every node the moment its recursion finishes, then reverse that finish order. Every edge now points forward, which schedules tasks with prerequisites and resolves build dependencies.

Practise on CodeStory's Depth-First Search practice problems and compare the order with Breadth-First Search.

Depth-First Search Code Example in Python

pythonRecursive and iterative DFS in Python over an adjacency list graph, both returning a valid visit order.

def dfs(graph, start):
    """Recursive DFS returning nodes in visit order."""
    visited, order = set(), []

    def explore(node):
        visited.add(node)
        order.append(node)
        for neighbor in graph[node]:      # graph: {node: [neighbors]}
            if neighbor not in visited:
                explore(neighbor)

    explore(start)
    return order


def dfs_iterative(graph, start):
    """Same traversal using an explicit stack instead of recursion."""
    visited, order, stack = set(), [], [start]
    while stack:
        node = stack.pop()
        if node in visited:
            continue
        visited.add(node)
        order.append(node)
        stack.extend(n for n in graph[node] if n not in visited)
    return order

Edit this code in the browser IDE on CodeStory, free on the platform. Open the CodeStory App

Depth-First Search Time and Space Complexity

TimeO(V + E) with an adjacency list, and O(V²) with an adjacency matrix
SpaceO(V) for the visited marks plus the recursion or stack depth

DFS touches every vertex and edge once, so the cost does not change between cases. Stack depth reaches O(V) on a single long path and stays shallower on bushy graphs and balanced trees.

Watch the Search Dive and Backtrack

Seeing the path go deep and then retreat to the last open junction makes the idea stick. Follow it on your own input, one step at a time.

When to Use Depth-First Search

  • You detect cycles in a directed graph, like circular dependencies in a build system, package manager or import graph.
  • You produce a topological order for tasks with prerequisites, like course scheduling or a job pipeline.
  • You count or label connected components and flood fill regions in a grid or network, like the number of islands problem.
  • You explore every path or configuration, which is the backbone of backtracking problems like mazes, N-Queens and permutations.

Mistakes to Avoid

  • Forgetting the visited set on a cyclic graph. DFS then loops forever or explores shared nodes again and again.
  • Hitting a stack overflow from deep recursion on large graphs. Switch to an explicit stack or raise the recursion limit when chains grow long.
  • Mixing up visited with currently on the recursion stack. Cycle detection in directed graphs needs a separate in progress state, known as three colour marking, and one visited flag is not enough.

Depth-First Search FAQs

Is depth-first search hard to learn?

No. Going as deep as you can and then backing up maps straight onto recursion, which most learners find intuitive once they see it work. Tricky parts include the visited set on graphs and very deep recursion, and both become habit quickly.

When should I use DFS instead of BFS?

Use DFS to explore full paths or the entire structure. Cycle detection, topological sort, connected components and backtracking all fit it. Use BFS for the shortest path in an unweighted graph or for level order, since BFS visits nodes in increasing distance from the start.

What is the time complexity of depth-first search?

O(V + E) with an adjacency list, where V counts vertices and E counts edges, because DFS examines every vertex and edge once. With an adjacency matrix the time becomes O(V²). Space is O(V) for the visited set plus the recursion or stack depth.

Can DFS work without recursion?

Yes. Replace the call stack with an explicit stack. Push the start node, then repeatedly pop a node, mark it visited and push its unvisited neighbours. This version avoids stack overflow on very deep graphs. Visit order can differ from the recursive version, and both are valid DFS.

How does DFS detect a cycle?

DFS marks nodes that sit on the current recursion path. If a neighbour is already on that path, an edge points back up the path, which closes a cycle. Directed graphs need this extra in progress mark.

How does DFS produce a topological order?

DFS records every node when its recursion finishes. Reversing that finish order puts every prerequisite before the tasks that depend on it.

How do I practise depth-first search on CodeStory?

Watch the search dive and backtrack in the visualiser, write the recursive version yourself, then try CodeStory's Depth-First Search practice problems.

Related Guides

Guides are step one. In a CodeStory batch you code DFS yourself, then explain every backtrack in a scored mock round.

Talk to a Mentor

Stuck on Depth-First Search? Get a Free Callback

Tell CodeStory which DFS step confuses you, and a mentor shapes your next steps.

  1. 1CodeStory finds your starting point, from your first call to interview ready.
  2. 2CodeStory explains online and campus batches, with timings for your mornings or evenings.
  3. 3You decide. No pressure, no payment on the call.

Get a Free Callback

I am a
I want to learn

CodeStory dials your number only for this callback.