DFS
Intermediate · 10 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Depth-first search follows one path as far as it can go, then backs up to the last fork and tries the next path. It is the natural way to walk a nested structure and uses recursion or a stack to remember where to return.
Practical use cases
- Web app: Listing every file in an upload folder. A file manager screen must show all files inside folders, and folders inside folders. The code opens a folder, dives into its first sub-folder, and returns when it is empty, then continues. This is how PHP functions that scan directories recursively work, and it handles any depth.
- Web app: Nested menu or category tree. A shop has Electronics > Phones > Android. To collect all products under Electronics, the code goes down each branch to the bottom, gathering items on the way, then comes back. One short recursive function covers a tree of any size.
- Web app: Maze-like form logic. A survey builder allows "if answer is yes, jump to question 7". To test that every path reaches the end, a checker follows each path to the finish, then backs up and tries the other answer. Dead ends are found before users hit them.
- System: Solvers and compilers. Puzzle solvers, compilers checking which function calls which, and tools that detect loops all follow one trail to its end before trying another. Backing up automatically is the key trick. In each of these the program never has to remember the whole map, only the trail back to the last fork, which is why recursion fits so naturally.
The story: Kabir and the Ball of Thread
Kabir and Mira entered the famous maze at an old haveli. Mira said, "If we try every turn a little at a time, we will be lost forever." Kabir tied one end of a ball of thread to the gate. "We will go as far as we can along one path, and unroll the thread as we go."
They took the first lane and the next and the next. At last they hit a dead end. Kabir did not start again. He simply pulled the thread back to the last junction and tried the next unexplored lane from there. When all lanes at that junction were done, back up one more junction.
Eventually every lane in the maze had been visited, and no lane was walked twice, because Mira kept a chalk mark at each junction they had visited. The thread always knew the way home.
That "dive deep, back up at dead ends" way of exploring is Depth-First Search. The thread is the stack (or the recursion) remembering where to return to.
How to spot this problem, and where you need it
You need to visit everything reachable in a nested or linked structure, or try one full path before another, and you do not care about shortest distance.
Signs you need it
- The data is nested: folders in folders, comments in comments, menus with submenus, or JSON of unknown depth.
- The problem says "explore all paths", "is there any route", "find a loop", or "visit everything connected".
- You wrote nested foreach loops that only handle two or three levels and break when the data goes deeper.
Where to use it in a project
- Recursive directory scans for backup, upload cleaning or search-in-files tools.
- Collecting all descendants of a category, a manager's whole team in an org chart, or every reply under a comment.
The solution
Write a function visit(node). Mark the node as seen, do your work on it, then call visit on each neighbour that is not yet seen. When a node has nothing new to visit, the function returns and you are automatically back at the previous fork. For a very deep structure, replace recursion with your own stack. The seen marks stop endless loops in graphs.
Payoff: Before: code that works for 2 levels of folders only. After: one 10-line function handles any depth and visits each item exactly once.
Explain it like I am 8
Pretend you explore a cave with a torch. Always take the first tunnel you see and keep going. When there is no tunnel left, walk back to the last place that had another tunnel and go down that one. Chalk marks stop you from visiting the same place twice.
How it works, step by step
- Mark the start vertex as visited and step into it.
- Look at each neighbour. If a neighbour is not visited yet, immediately dive into it (recursion) before checking the other neighbours.
- When a vertex has no unvisited neighbours, it is finished. Return to the vertex you came from.
- Keep going until you are back at the start with nothing left to try.
- A recursive call uses the call stack. An iterative version uses your own stack: same idea, no recursion limit worries.
The code in four languages
PHP
<?php
// graph: adjacency list. Returns the order in which vertices were visited.
function dfs(array $graph, string $start): array {
$visited = [];
$order = [];
$visit = function (string $node) use (&$visit, &$visited, &$order, $graph): void {
$visited[$node] = true; // chalk mark
$order[] = $node;
foreach ($graph[$node] as $next) {
if (!isset($visited[$next])) {
$visit($next); // dive deeper BEFORE the other neighbours
}
} // loop ends = dead end, return = pull the thread back
};
$visit($start);
return $order;
}
$graph = [
'A' => ['B', 'C'], 'B' => ['A', 'D', 'E'], 'C' => ['A', 'F'],
'D' => ['B'], 'E' => ['B', 'F'], 'F' => ['C', 'E'],
];
echo implode(' -> ', dfs($graph, 'A')); // A -> B -> D -> E -> F -> CJavaScript
// graph: adjacency list. Returns the order in which vertices were visited.
function dfs(graph, start) {
const visited = new Set();
const order = [];
function visit(node) {
visited.add(node); // chalk mark
order.push(node);
for (const next of graph[node]) {
if (!visited.has(next)) {
visit(next); // dive deeper BEFORE the other neighbours
}
} // loop ends = dead end, return = pull the thread back
}
visit(start);
return order;
}
const graph = {
A: ['B', 'C'], B: ['A', 'D', 'E'], C: ['A', 'F'],
D: ['B'], E: ['B', 'F'], F: ['C', 'E'],
};
console.log(dfs(graph, 'A').join(' -> ')); // A -> B -> D -> E -> F -> CJava
import java.util.*;
public class Main {
// graph: adjacency list. Returns the order in which vertices were visited.
static List<String> dfs(Map<String, List<String>> graph, String start) {
Set<String> visited = new HashSet<>();
List<String> order = new ArrayList<>();
visit(graph, start, visited, order);
return order;
}
static void visit(Map<String, List<String>> graph, String node, Set<String> visited, List<String> order) {
visited.add(node); // chalk mark
order.add(node);
for (String next : graph.get(node)) {
if (!visited.contains(next)) {
visit(graph, next, visited, order); // dive deeper BEFORE the other neighbours
}
} // loop ends = dead end, return = pull the thread back
}
public static void main(String[] args) {
Map<String, List<String>> graph = Map.of(
"A", List.of("B", "C"), "B", List.of("A", "D", "E"), "C", List.of("A", "F"),
"D", List.of("B"), "E", List.of("B", "F"), "F", List.of("C", "E"));
System.out.println(String.join(" -> ", dfs(graph, "A"))); // A -> B -> D -> E -> F -> C
}
}Go
package main
import (
"fmt"
"strings"
)
// dfs returns the order in which vertices were visited.
func dfs(graph map[string][]string, start string) []string {
visited := map[string]bool{}
var order []string
var visit func(node string)
visit = func(node string) {
visited[node] = true // chalk mark
order = append(order, node)
for _, next := range graph[node] {
if !visited[next] {
visit(next) // dive deeper BEFORE the other neighbours
}
} // loop ends = dead end, return = pull the thread back
}
visit(start)
return order
}
func main() {
graph := map[string][]string{
"A": {"B", "C"}, "B": {"A", "D", "E"}, "C": {"A", "F"},
"D": {"B"}, "E": {"B", "F"}, "F": {"C", "E"},
}
fmt.Println(strings.Join(dfs(graph, "A"), " -> ")) // A -> B -> D -> E -> F -> C
}Time: O(V + E) · Extra space: O(V). Each vertex is entered once and each edge is looked at about once. Space is the visited marks plus the stack depth.
Watch out for
- Forgetting the visited marks. On a graph with a loop, DFS then walks round and round forever.
- Very deep graphs (a long chain of a hundred thousand vertices) can overflow the recursion stack. Use an explicit stack instead.
- Expecting DFS to find the shortest path. It finds a path, not the shortest.
Quick check
- DFS uses which structure to remember where to back up to?
- Queue
- Heap
- Stack (or recursion)
- What does DFS do first when it visits a vertex with several unvisited neighbours?
- Dives into the first neighbour completely
- Visits all neighbours one level at a time
- Sorts the neighbours
- Time complexity of DFS on an adjacency list?
- O(V²)
- O(V + E)
- O(log V)