Articles / AI · Part 15

Depth-First Search (DFS)

Learn how Depth-First Search explores a search tree by following one branch deeply before backtracking. Understand stacks, the DFS algorithm, Python implementation, complexity, advantages, limitations, and applications.

Depth-First Search (DFS)

Imagine you are standing at the entrance of a maze. There are several paths in front of you. You choose one and keep moving forward. At every junction, you continue along the path you selected until you reach a dead end or find the exit.

If you reach a dead end, you return to the last junction where another path was available and try that one.

This is the basic idea behind Depth-First Search (DFS).

In Artificial Intelligence, searching does not always mean checking every possible option at the same level. Sometimes, an algorithm explores one direction as deeply as possible before considering other possibilities.

Depth-First Search follows exactly this approach.

Depth-First Search (DFS) is an uninformed search algorithm that explores a branch of a search tree as deeply as possible before backtracking to explore other branches.

It begins at the initial node, visits one of its neighbouring nodes, and continues moving deeper until it cannot go further. It then returns to an earlier node and explores another available branch.

Unlike Breadth-First Search (BFS), which explores nodes level by level, DFS prioritises depth.

2. How Does DFS Work?

Consider the following search tree:

             A
           /   \
          B     C
         / \   / \
        D   E F   G

Assume we start from node A and explore from left to right.

The DFS traversal will be:

A → B → D → E → C → F → G

Let’s understand the process:

  1. Start at A.
  2. Move to B, the left child of A.
  3. Move deeper to D.
  4. D has no unvisited children, so return to B.
  5. Explore B’s other child, E.
  6. After finishing B’s branch, return to A.
  7. Move to C.
  8. Visit F and then G.

Notice that DFS completely explores one branch before moving to another.

This process of returning to an earlier node to explore another branch is called backtracking.

3. The Role of a Stack in DFS

DFS uses a data structure called a Stack.

A stack follows the principle of LIFO (Last In, First Out). This means the last element added to the stack is the first one removed.

Think of a stack of books. When you place a new book on top, that is the first book you can take away.

DFS uses this behaviour to keep track of which nodes it should explore next.

There are two common ways to implement DFS:

  • Iterative DFS: Uses an explicit stack.
  • Recursive DFS: Uses function calls and the program’s call stack.

Both approaches follow the same basic search strategy.

4. DFS Algorithm

The general steps of Depth-First Search are:

  1. Start with the initial node.
  2. Mark the node as visited.
  3. Check its unvisited neighbours.
  4. Choose one neighbour and explore it.
  5. Continue until no unvisited neighbour remains.
  6. Backtrack to the previous node.
  7. Repeat until all reachable nodes have been explored or the goal is found.

A visited set is particularly important when searching graphs. It prevents the algorithm from repeatedly visiting the same node and getting trapped in a cycle.

5. Implementing DFS in Python

Let’s implement DFS using Python.

We will represent the search tree as a graph using an adjacency list.

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

def dfs(graph, start):
    visited = set()
    stack = [start]

    while stack:
        node = stack.pop()

        if node not in visited:
            print(node, end=" ")
            visited.add(node)

            # Reverse the neighbours to explore left to right
            for neighbour in reversed(graph[node]):
                if neighbour not in visited:
                    stack.append(neighbour)

dfs(graph, 'A')

Output: A B D E C F G

Let’s understand the important parts:

  • stack = [start] creates a stack containing the starting node.
  • stack.pop() removes the most recently added node.
  • visited keeps track of nodes already explored.
  • reversed(graph[node]) ensures that the leftmost neighbour is processed first in this example.

The order in which neighbours are added matters. DFS can produce a different traversal order depending on how the neighbours are arranged.

6. Finding a Goal Using DFS

Traversal and goal searching are related, but they are not exactly the same.

In traversal, we want to visit reachable nodes. In goal searching, we stop when we find a particular target.

Let’s search for node G:

def dfs_search(graph, start, goal):
    visited = set()
    stack = [start]

    while stack:
        node = stack.pop()

        if node == goal:
            return True

        if node not in visited:
            visited.add(node)

            for neighbour in reversed(graph[node]):
                if neighbour not in visited:
                    stack.append(neighbour)

    return False


print(dfs_search(graph, 'A', 'G'))

Output: True

The algorithm returns True when it finds the goal. If the goal cannot be reached, it returns False.

In a path-finding problem, we can also store parent information to reconstruct the path from the starting node to the goal.

7. Properties of DFS

To understand the performance of a search algorithm, we commonly examine four properties.

Completeness

Completeness means whether an algorithm is guaranteed to find a solution if one exists.

DFS is not complete in general when the search space can have infinite-depth paths or cycles. It may keep exploring one path forever without reaching a solution elsewhere.

However, DFS can be complete in a finite graph when visited-node tracking is used and all reachable nodes are eventually explored.

Optimality

Optimality means whether an algorithm is guaranteed to find the best or lowest-cost solution.

DFS is not optimal. It may find a solution, but that solution may not be the shortest or least expensive one.

Time Complexity

In the usual tree-search model:

\[
O(b^m)
\]

Here:

  • \(b\) = branching factor, or the average number of successors per node.
  • \(m\) = maximum depth of the search tree.

The number of nodes can grow rapidly as the search goes deeper.

Space Complexity

The usual tree-search space complexity is:

\[
O(bm)
\]

DFS generally stores the current path and the unexplored alternatives, rather than keeping every node at an entire level in memory.

For graph-search implementations, the visited set can require additional memory, depending on the number of vertices.

8. Advantages of DFS

  • Memory efficient: It generally requires less memory than BFS in large, wide search trees.
  • Simple to implement: It can be implemented using a stack or recursion.
  • Can reach deep solutions quickly: It may find a solution without exploring every shallow node first.
  • Useful for graph exploration: It can help identify connected components, cycles, and other graph properties.

9. Limitations of DFS

  • Not always complete: It can get stuck exploring an infinite path.
  • Not optimal: It does not guarantee the shortest or least-cost solution.
  • Can explore an unhelpful branch: The first path it chooses may lead far away from the goal.
  • Sensitive to neighbour order: Changing the order of successors can change which branch is explored first.

10. Applications of DFS

DFS is useful in several areas of computer science and Artificial Intelligence:

  • Maze solving: Exploring a path until reaching an exit or dead end.
  • Graph traversal: Visiting all reachable nodes in a graph.
  • Cycle detection: Identifying cycles in directed and undirected graphs.
  • Dependency analysis: Exploring relationships between tasks or components.
  • Backtracking problems: Exploring possible arrangements in puzzles and constraint problems.
  • Path exploration: Investigating possible routes through a search space.

DFS is also an important foundation for more advanced graph algorithms.

11. DFS vs BFS

Both Depth-First Search and Breadth-First Search are uninformed search algorithms, but they explore the search space differently.

Feature DFS BFS
Search approach Goes deep first Explores level by level
Data structure Stack Queue
Memory usage Usually lower in tree search Usually higher
Complete Not always Yes, with finite branching
Optimal No Yes, when all step costs are equal
Typical time complexity (O(b^m)) (O(b^{d+1}))

Here, \(d\) is the depth of the shallowest goal, while \(m\) is the maximum depth of the search tree.

The important difference is simple: BFS explores broadly, while DFS explores deeply.

Neither algorithm is best for every problem. The choice depends on the structure of the search space and what we want to find.

Conclusion

Depth-First Search teaches us an important idea in problem-solving: sometimes, instead of exploring every available option, we follow one direction until we can go no further.

Its stack-based approach makes it simple and often memory-efficient. However, it does not guarantee the shortest solution and can struggle with infinite search paths.

In the next article, we will explore two approaches that address one of DFS’s major limitations: Depth-Limited Search and Iterative Deepening Search.

Quick quiz

5 questions
What is the main idea behind Depth-First Search?
Which data structure is commonly used in iterative DFS?
What does backtracking mean in DFS?
Is DFS guaranteed to find the shortest path?
What is the usual time complexity of DFS in a tree-search model?

Keep a copy

Read offline as a printout or PDF.

farhanpaal.com

Keep reading

Ask Farhan

Ask anything about Farhan