AlgoMaster Logo

Introduction to Depth-First Search (DFS)

High Priority16 min readUpdated November 9, 2026
Listen to this chapter
Unlock Audio

Premium Video

This video is available to premium subscribers only

Unlock Full Access

Depth-First Search, or DFS, is one of the most important graph traversal algorithms and a fundamental concept for coding interviews.

The idea is simple. Start at a node, follow one path as deeply as possible, and then work your way back to explore other paths.

In this chapter, we'll understand how DFS works, walk through an example step by step, implement it using recursion and iteration, handle graphs with more than one component, analyze its time and space complexity, and look at common interview problems where DFS is useful.

How DFS Works

Loading simulation...

We start at a node and move to one of its unvisited neighbors. From there, we move to another unvisited neighbor, and keep going as deep as we can.

But what happens when we reach a node with no unvisited neighbors?

We go back to the previous node and look for another path we haven't explored. This process of going back is called backtracking.

And that's essentially how DFS works. We keep moving deeper whenever possible, and backtrack whenever we reach a dead end. This continues until we've visited every node reachable from our starting point.

Think of it like exploring a maze:

  1. You pick a path and follow it until you hit a dead end.
  2. Then you go back to the last junction and try another unexplored path.
  3. By keeping track of where you've already been, you avoid going around in circles.

DFS follows the same basic idea. It works on anything that can be modeled as nodes and edges, including graphs, trees, tries, and 2D grids.

Let's see it in action.

The Example Graph

Consider this undirected graph with six nodes, numbered from 0 to 5.

  • Node 0 is connected to nodes 1 and 2.
  • Node 1 is connected to nodes 3 and 4.
  • Node 2 is connected to node 5.
  • Node 4 is also connected to node 5.

Notice that this graph contains a cycle. We can start at 0, move through 1, 4, 5, and 2, and eventually return to 0.

In code, we'll store this graph as an adjacency list, where index i holds the list of neighbors of node i:

Node

Neighbors

0

1, 2

1

0, 3, 4

2

0, 5

3

1

4

1, 5

5

2, 4

Now, let's perform DFS starting from node 0. Whenever we have multiple unvisited neighbors, we'll choose the one with the smaller number first. That's why each neighbor list above is sorted. This keeps the traversal order consistent, so you can follow along and get the same result.

Tracing DFS Step by Step

Going Deep

We start at node 0 and mark it as visited.

Node 0 has two neighbors: 1 and 2. Both are unvisited, so we choose node 1.

We move to node 1 and mark it as visited.

Now, node 1 has three neighbors: 0, 3, and 4. Node 0 has already been visited, so we skip it.

Next is node 3. We move to node 3 and mark it as visited.

Even though node 2 is directly connected to our starting node, 0, we haven't visited it yet. That's because DFS doesn't explore all nearby nodes first. Instead, it follows one path as deeply as possible before trying another.

Now, node 3 has only one neighbor, node 1, which we've already visited. So there's nowhere else to go.

What do we do next?

Backtracking

Since node 3 has no unvisited neighbors, we backtrack to node 1.

Node 1 still has another neighbor we haven't explored: node 4. So we move to node 4 and mark it as visited.

From node 4, we skip node 1 because it's already visited. Then we move to node 5 and mark it as visited.

Node 5 has an unvisited neighbor, node 2. So we move to node 2 and mark it as visited.

Node 2 has two neighbors, 0 and 5, but both have already been visited. So we've reached another dead end.

Time to backtrack again.

Finishing the Traversal

From node 2, we return to node 5. Node 5 has no unvisited neighbors left, so we go back to node 4.

The same goes for node 4, so we return to node 1. And since node 1 has explored all its neighbors, we go back to node 0.

Now, node 0 still has one neighbor left to check: node 2. But we've already visited node 2 through a different path, so we skip it.

And that's it. Our DFS traversal is complete.

The table below collects every step of the trace. The "Current path" column shows the chain of nodes from the start to where we are, which is the route we would retrace when backtracking.

Scroll

Step

At node

Action

Current path

Visit order

1

0

Visit 0

0

0

2

0

Move to 1, visit it

0, 1

0, 1

3

1

Skip 0 (visited), move to 3, visit it

0, 1, 3

0, 1, 3

4

3

Dead end, backtrack to 1

0, 1

0, 1, 3

5

1

Move to 4, visit it

0, 1, 4

0, 1, 3, 4

6

4

Skip 1 (visited), move to 5, visit it

0, 1, 4, 5

0, 1, 3, 4, 5

7

5

Move to 2, visit it

0, 1, 4, 5, 2

0, 1, 3, 4, 5, 2

8

2

0 and 5 visited, dead end, backtrack to 5

0, 1, 4, 5

0, 1, 3, 4, 5, 2

9

5, 4, 1

Nothing left, backtrack through 4 and 1 to 0

0

0, 1, 3, 4, 5, 2

10

0

Skip 2 (visited), traversal complete

(empty)

0, 1, 3, 4, 5, 2

The final visit order is 0, 1, 3, 4, 5, 2.

The diagram below shows the same traversal on the graph. The numbered edges are the ones DFS walked along, in order. The dotted edge from 0 to 2 was checked at the very end and skipped, because node 2 was already visited.

Here's an important thing to notice. Even though node 2 is directly connected to node 0, DFS reached it through a much longer path: 0, 1, 4, 5, 2.

That's because DFS doesn't guarantee the shortest path between two nodes. If we need the shortest path in an unweighted graph, Breadth-First Search, or BFS, is usually a better choice.

Throughout this traversal, we needed to keep track of two important things. Let's understand what they are and why we need them.

Why We Need a Visited Set

The first thing we need is a way to remember which nodes we've already visited.

But why is that important?

Imagine running DFS without keeping track of visited nodes. We start at node 0 and move to node 1. From node 1, we see node 0 as a neighbor, so we go back to 0. Then we move to 1 again. And we keep going back and forth forever.

The same thing can happen with larger cycles, like the one through 0, 1, 4, 5, and 2 in our graph.

To avoid this, we maintain a visited set:

  • Whenever we visit a node, we immediately mark it as visited.
  • Before exploring any neighbor, we check whether it's already been visited.

This ensures we process each node at most once, even when the graph contains cycles. When the nodes are numbered from 0 to n - 1, as in our example, a boolean array of size n works as the visited set. For other node types, such as strings or grid coordinates, a hash set works the same way.

Why DFS Uses a Stack

The second thing we need is a way to remember where to return when we reach a dead end.

Think back to our example. When we reached node 2, we backtracked to 5, then 4, then 1, and finally 0.

Notice the pattern. We always return to the node we came from most recently.

This follows the Last In, First Out, or LIFO, principle. And that's exactly how a stack works.

At the deepest point of our traversal, we have 0, 1, 4, 5, and 2 on our path. Whenever we move deeper, we add another node. And whenever we backtrack, we remove the most recent node and return to the previous one.

Here is the path at that deepest point, viewed as a stack with 2 on top:

0
1
4
5
2
top

Backtracking pops 2, then 5, then 4, then 1, which leaves us back at 0, exactly the order we traced above.

There are two common ways to implement this behavior:

  1. Recursion, which automatically manages the stack through the function call stack.
  2. An explicit stack that we maintain ourselves.

Let's look at both approaches.

Recursive Implementation

Let's start with the recursive approach.

We'll represent our graph using an adjacency list, where each node has a list of its neighbors. In Java, we can represent this using a List<List<Integer>>.

We'll also maintain a boolean array called visited to keep track of which nodes we've already explored.

Our recursive DFS function takes three things: the graph, the current node, and the visited array. It works like this:

  1. First, we mark the current node as visited. This is also where we process the node, such as adding it to our traversal result. In the code below, we print it.
  2. Next, we go through each of its neighbors.
  3. For every neighbor, we check whether it's already been visited.
  4. If not, we recursively call DFS on that neighbor.

And that's essentially the entire algorithm. To run it on our example, we create a visited array of size 6, all set to false, and call dfs(graph, 0, visited). It prints 0 1 3 4 5 2.

But you might be wondering, where does backtracking happen?

The interesting part is that we don't need any special code for it. When a recursive call finishes exploring all the neighbors of a node, it automatically returns to the previous function call. And execution continues from where it left off, checking the remaining neighbors.

For example, when DFS finishes exploring node 3, it returns to node 1, which then moves on to node 4.

You can see this in the chain of calls for our example. Each level of indentation is one frame on the call stack, and a call returns when its loop over neighbors ends:

That's how recursion handles backtracking naturally.

Iterative Implementation

Now, let's implement DFS without using recursion.

Instead of relying on the function call stack, we'll maintain our own stack. In Java, we can use an ArrayDeque for this.

  1. We start by pushing our starting node onto the stack.
  2. Then, as long as the stack isn't empty, we pop the top node.
  3. If it's already visited, we simply skip it.
  4. Otherwise, we mark it as visited, process it, and push its unvisited neighbors onto the stack.

There are two things worth noting here.

First, because a stack follows LIFO order, we push neighbors in reverse order if we want smaller-numbered neighbors to be processed first. For node 0, we push 2 and then 1, so 1 ends up on top and gets popped next. Without the reversal, the traversal is still a valid DFS, just in a different order.

Second, the same node can sometimes be pushed onto the stack more than once. A node can be unvisited when one neighbor pushes it and still be sitting on the stack when another neighbor pushes it again. That's why we check whether a node has already been visited after popping it.

Iterative Walkthrough

Let's walk through our example. We'll use the same graph, and describe the stack from bottom to top.

First, we push node 0.

We pop 0, mark it as visited, and push its neighbors in reverse order: 2, then 1. Our stack now contains 2 and 1, with 1 at the top.

Next, we pop node 1 and mark it as visited. Node 0 is already visited, so we push only its unvisited neighbors in reverse order: 4, then 3. The stack now contains 2, 4, 3.

We pop 3 and mark it as visited. Since it has no unvisited neighbors, there's nothing to push.

Next, we pop 4, mark it as visited, and push node 5. Our stack now contains 2 and 5.

We pop 5, mark it as visited, and push its unvisited neighbor, node 2.

Now, notice something interesting. We have two copies of node 2 on the stack. One was pushed earlier when we explored node 0, and the other came from node 5.

We pop the top copy of node 2 and mark it as visited. Both its neighbors have already been visited, so we don't push anything.

Finally, we pop the remaining copy of node 2. But since it's already visited, we skip it.

The stack is now empty, and our traversal is complete.

Here is the full trace:

Scroll

Step

Pop

Action

Stack after (bottom to top)

Visit order

0

-

Push 0

0

 

1

0

Visit 0, push 2, 1

2, 1

0

2

1

Visit 1, push 4, 3

2, 4, 3

0, 1

3

3

Visit 3, nothing to push

2, 4

0, 1, 3

4

4

Visit 4, push 5

2, 5

0, 1, 3, 4

5

5

Visit 5, push 2

2, 2

0, 1, 3, 4, 5

6

2

Visit 2, nothing to push

2

0, 1, 3, 4, 5, 2

7

2

Already visited, skip

(empty)

0, 1, 3, 4, 5, 2

The final visit order is 0, 1, 3, 4, 5, 2. Exactly the same as our recursive traversal.

Handling Disconnected Graphs

So far, we've worked with a connected graph.

But what if our graph has multiple disconnected components?

Suppose we add two more nodes, 6 and 7, which are connected only to each other.

If we start DFS from node 0, we'll never reach these two nodes. That's because DFS only visits nodes reachable from its starting point.

So how do we explore the entire graph?

We simply go through every node. Whenever we find a node that hasn't been visited, we start a new DFS from that node. And we use the same visited array across all these traversals, so a node visited by one DFS is never started from again.

In an undirected graph, each new DFS explores one complete connected component. So by counting how many times we start DFS, we can also count the connected components.

In our example, there are two. The loop starts a DFS at node 0, which visits 0 through 5. Nodes 1 to 5 are then skipped because they're already visited. The loop reaches node 6, which is unvisited, so it starts a second DFS that visits 6 and 7. Node 7 is skipped, and the loop ends with a count of 2.

The code below puts this into practice. It reuses the recursive DFS from earlier, without the print, and returns the number of components:

Time and Space Complexity

Now, let's analyze the time and space complexity of DFS. Let V represent the number of vertices and E represent the number of edges.

Time Complexity

Assuming we're using an adjacency list, each node is visited at most once. And when we visit a node, we examine all its neighbors.

Across the entire graph, we visit every vertex and examine every edge. In an undirected graph, each edge appears in the neighbor lists of both its endpoints, so it gets examined twice. In a directed graph, it appears once. Either way, the work on edges grows in proportion to E.

So the overall time complexity is O(V + E). This also holds when we loop over every node to handle disconnected graphs, because the shared visited array still lets each node be visited only once.

Space Complexity

We maintain a visited array, which requires O(V) space.

In the recursive approach, the call stack can grow to a depth of V in the worst case. That happens when the graph is one long path, such as 0 to 1 to 2 and onward, because DFS descends through every node before it can return. So its auxiliary space complexity is O(V).

In our iterative implementation, the stack can contain multiple copies of the same node, as we saw with node 2. Since the total number of pushes is bounded by the number of edges, its auxiliary space complexity is O(V + E).

Scroll

Implementation

Time

Auxiliary space

Recursive

O(V + E)

O(V) for the visited array and the call stack

Iterative

O(V + E)

O(V + E) for the visited array and the stack with duplicate entries

These bounds don't include the adjacency list itself, which takes O(V + E) space on its own.

Recursion Depth

One practical thing to keep in mind is recursion depth. If the graph contains a very long path, recursive DFS can cause a stack overflow. For example, Java's default thread stack usually allows recursion depths in the thousands to low tens of thousands, depending on how much each frame holds, so a path of 100,000 nodes can fail.

Iterative DFS avoids this call-stack limitation, making it a safer choice for very deep graphs. Its stack lives on the heap, which has far more room than the call stack.

Where DFS Is Used

Now, let's look at where DFS is useful in coding interviews.

DFS isn't limited to graphs represented using adjacency lists. We can use it whenever we need to explore connected elements or follow paths through a structure.

Binary Trees

Take binary trees, for example. Preorder, inorder, and postorder traversals are all variations of DFS. They differ only in when the current node is processed relative to its left and right subtrees.

And since trees don't contain cycles, we don't need a visited set when traversing from the root. Every node is reached through exactly one path from the root, so DFS can never arrive at the same node twice.

Grid Traversal

Another common application is grid traversal. Here, each cell is a node, and the cells above, below, to the left, and to the right of it are its neighbors.

Consider the Number of Islands problem. We're given a grid containing land and water, and we need to count how many islands it contains.

We scan the grid, and whenever we find an unvisited land cell, we start DFS to explore and mark all the land cells connected to it. Each DFS explores one complete island. So counting how many times we start DFS gives us the total number of islands.

This is the same idea as counting connected components, applied to a grid instead of an adjacency list.

Backtracking Problems

DFS is also closely related to backtracking problems. For example, when generating subsets or permutations, we make a choice, explore where it leads, and then undo that choice to try another possibility. This is DFS over a tree of choices, where each path from the root to a leaf is one complete answer.

Other Graph Problems

DFS is also the base for several classic graph algorithms. Cycle detection tracks the nodes on the current path and reports a cycle when DFS reaches one of them again. Topological sorting of a directed acyclic graph records each node after DFS finishes all of its descendants, then reverses that order.

When to Use DFS

Whenever a problem involves exploring connected elements, finding paths, or trying different combinations, DFS is often a good starting point.

But if you need the shortest path in an unweighted graph, or want to explore nodes level by level, BFS is usually a better fit.

Problem asks for

Use

Exploring connected elements, such as components or islands

DFS

Finding any path, or every path, between two nodes

DFS

Trying every combination, such as subsets or permutations

DFS (backtracking)

The shortest path in an unweighted graph

BFS

Processing nodes level by level

BFS

Conclusion

Depth-First Search explores one path as deeply as possible before backtracking to try other paths.

We use a visited set to avoid processing the same node multiple times, and a stack to keep track of our traversal. We can implement that stack implicitly through recursion or explicitly using an iterative approach.

DFS runs in O(V + E) time, and it applies to graphs, trees, grids, and backtracking problems.

To make these concepts stick, try tracing both implementations yourself on the six-node graph from this chapter, and check that you get the visit order 0, 1, 3, 4, 5, 2. Then practice with problems like Number of Islands and Clone Graph.

Quiz

Depth-First Search Quiz

10 quizzes