Depth-first search (DFS) follows one path as far as it can, and only when it hits a dead end does it backtrack to the most recent vertex with an unexplored edge. It needs nothing more than recursion (or an explicit stack) and runs in O(V + E). DFS does not find shortest paths, but the order in which it enters and leaves vertices reveals the structure of a graph: cycles, components, ancestors, and the basis for topological sort, strongly connected components and bridges.
Think of it like
Exploring a maze with a ball of thread
Theseus walks into the labyrinth unrolling a thread. At each junction he takes an unexplored corridor and keeps going. When he reaches a dead end, he winds the thread back to the last junction that still has an untried corridor. Chalk marks on visited junctions stop him from walking in circles. The thread is the recursion stack, the chalk marks are the visited set, and winding back is backtracking.
How it works
Calling dfs(u) marks u as visited and then, for each neighbor v that is still unvisited, immediately calls dfs(v). The call for u returns only after everything reachable through its unvisited neighbors has been explored. That gives every vertex two moments: when it is discovered (entered) and when it is finished (left).
- 1
Enter the vertex
Mark
uvisited and record its discovery time. Any pre-order work (printing, labeling a component) happens here. - 2
Try each neighbor
For each
vinadj[u]: ifvis unvisited, recurse into it. Visited neighbors are skipped (or classified, see below). - 3
Finish the vertex
When every neighbor has been handled, record the finish time and return. Post-order work (topological order, low-links) happens here.
- 4
Cover every component
Loop over all vertices and start a new DFS from each one that is still unvisited, so disconnected parts are not missed.
def dfs(u: int) -> None:
visited[u] = True # discovery: pre-order work goes here
for v in adj[u]:
if not visited[v]:
dfs(v) # go deep before trying u's next neighbor
# finish: post-order work goes here
for u in range(n): # restart from every unvisited vertex
if not visited[u]:
dfs(u)Iterative DFS with an explicit stack
Replacing recursion with a stack is easy for simple reachability: pop a vertex, skip it if already visited, otherwise mark it and push its unvisited neighbors. Pushing neighbors in reverse makes it visit vertices in the same order as the recursive version. The stack may hold O(E) entries because a vertex can be pushed by several neighbors before it is popped.
def dfs_iterative(adj: list[list[int]], start: int) -> list[int]:
visited = [False] * len(adj)
order = []
stack = [start]
while stack:
u = stack.pop()
if visited[u]:
continue # pushed more than once; already handled
visited[u] = True
order.append(u)
for v in reversed(adj[u]): # reversed so neighbors are visited in list order
if not visited[v]:
stack.append(v)
return orderDiscovery and finish times
Keep a global clock that ticks on every discovery and every finish. disc[u] is when u was entered and fin[u] is when it was left. Because a call only returns after all of its sub-calls return, the intervals [disc, fin] nest like parentheses.
Run DFS on the directed graph A→B, A→C, B→C, C→A, D→C, D→E, starting from A and scanning neighbors alphabetically. After A's tree is finished, D is the next unvisited vertex and starts a second tree.
| Vertex | disc | fin | Interval |
|---|---|---|---|
| A | 1 | 6 | [1, 6] contains B and C |
| B | 2 | 5 | [2, 5] contains C |
| C | 3 | 4 | [3, 4] is a leaf of the first tree |
| D | 7 | 10 | [7, 10] starts a new tree, disjoint from A's |
| E | 8 | 9 | [8, 9] nested inside D |
Edge classification
Color each vertex white (undiscovered), gray (discovered, still on the recursion stack) or black (finished). When DFS examines an edge u → v, the color of v tells you what kind of edge it is.
- Tree edge
vis white. DFS descends through this edge; tree edges form the DFS forest.- Back edge
vis gray, sovis an ancestor ofustill on the stack. A back edge closes a cycle.- Forward edge
vis black anddisc[u] < disc[v]: a shortcut to a descendant that is already finished.- Cross edge
vis black anddisc[v] < disc[u]: an edge to a vertex in a different, already-finished branch or tree.
| Edge | Type | Why |
|---|---|---|
| A → B | Tree | B is white when explored |
| B → C | Tree | C is white when explored |
| C → A | Back | A is gray: the cycle A → B → C → A |
| A → C | Forward | C is black and disc[A] = 1 < disc[C] = 3 |
| D → C | Cross | C is black and disc[C] = 3 < disc[D] = 7 |
| D → E | Tree | E is white when explored |
Cycle detection
Undirected graphs: track the parent
In an undirected graph every edge appears in both adjacency lists, so the edge you just walked down leads straight back to your parent. Ignore that one edge; any other edge to an already-visited vertex is a back edge, and therefore a cycle. If the graph can contain parallel edges, skip the parent edge id rather than the parent vertex, since two parallel edges form a genuine cycle of length 2.
Directed graphs: three colors
A directed graph has a cycle if and only if DFS finds a back edge, which means an edge to a gray vertex. A plain visited flag is not enough: reaching a black vertex through a forward or cross edge (like D → C above) is perfectly legal and does not imply a cycle.
Undirected cycle check
- Two states suffice: visited or not
- Visited neighbor that is not the parent ⇒ cycle
- Union-find is an equally good alternative
- A connected graph with
E ≥ Vmust contain a cycle
Directed cycle check
- Three states: white, gray, black
- Edge to a gray vertex ⇒ cycle
- Edges to black vertices are never cycles
- Equivalent: Topological Sort fails to order every vertex
Connected components and flood fill
To label components, loop over the vertices and start a fresh DFS from each unvisited one; everything that DFS reaches gets the same label. Every vertex and edge is touched once, so labeling all components costs O(V + E) in total.
Flood fill is the same idea on a grid: the paint-bucket tool in an image editor recolors the connected region of same-colored pixels around the click. Counting islands, measuring the largest island, or capturing surrounded regions are all flood fills. The visualization above shows the search diving down one branch at a time.
def num_islands(grid: list[list[str]]) -> int:
rows, cols = len(grid), len(grid[0])
islands = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] != "1":
continue
islands += 1 # unvisited land: a new component
grid[r][c] = "0" # sink it so it is never counted again
stack = [(r, c)]
while stack:
cr, cc = stack.pop()
for nr, nc in ((cr + 1, cc), (cr - 1, cc), (cr, cc + 1), (cr, cc - 1)):
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == "1":
grid[nr][nc] = "0"
stack.append((nr, nc))
return islandsDFS vs BFS
| Need | Use | Reason |
|---|---|---|
| Fewest edges between two vertices | BFS | BFS visits vertices in distance order; DFS does not |
| Count or label components | Either | Both visit every reachable vertex once |
| Detect a directed cycle | DFS | Gray vertices identify back edges |
| Topological order, SCCs, bridges | DFS | These rely on finish times or low-links |
| Enumerate all paths or configurations | DFS (backtracking) | The recursion stack is the current path |
| Very wide but shallow graph | DFS | Memory is O(depth), BFS is O(width) |
Complexity
Each vertex is discovered once, and each adjacency list is scanned once in total, so DFS is O(V + E) with adjacency lists and O(V²) with a matrix. Extra space is O(V) for colors or times plus the stack, whose depth is the length of the longest path DFS follows, up to V.
Complexity
| Variant | Time | Space | Notes |
|---|---|---|---|
| Recursive DFS, adjacency list | O(V + E) | O(V) | Recursion depth up to V |
| Iterator-stack DFS | O(V + E) | O(V) | Supports finish times without recursion |
| Push-all-neighbors stack DFS | O(V + E) | O(E) | A vertex may be pushed once per neighbor |
| DFS, adjacency matrix | O(V²) | O(V) | Each row scan costs O(V) |
| Grid flood fill (R × C) | O(R · C) | O(R · C) | Worst case: the whole grid is one region |
| Directed cycle check (3 colors) | O(V + E) | O(V) | Stops at the first back edge |
Implementation
Label every vertex of an undirected graph with a component id. Each unvisited start vertex begins a new component.
import sys
def connected_components(adj: list[list[int]]) -> tuple[int, list[int]]:
sys.setrecursionlimit(max(1000, 2 * len(adj) + 10)) # recursion can be V deep
comp = [-1] * len(adj) # -1 = not visited yet
def dfs(u: int, label: int) -> None:
comp[u] = label
for v in adj[u]:
if comp[v] == -1:
dfs(v, label)
count = 0
for start in range(len(adj)):
if comp[start] == -1: # unvisited vertex: a new component
dfs(start, count)
count += 1
return count, compKey takeaways
- DFS goes deep first using recursion or a stack and runs in
O(V + E); it does not find shortest paths. - Discovery and finish times nest like parentheses, which encodes ancestor and descendant relationships.
- Edges classify as tree, back, forward or cross; a back edge exists exactly when a directed graph has a cycle.
- Undirected cycle detection skips the parent edge; directed cycle detection needs white, gray and black.
- Components, flood fill, topological sort, SCCs and bridges are all DFS with a little bookkeeping.
- Recursion depth can reach
V; switch to an explicit stack for deep graphs and large grids.
Common pitfalls
- Using a single
visitedflag for directed cycle detection and reporting cycles on harmless cross edges. - In undirected graphs, treating the edge back to the parent as a cycle, or skipping the parent vertex when parallel edges exist.
- Hitting a recursion limit or stack overflow on long paths (
10⁵vertices in a line, large grids). - Forgetting the outer loop over all vertices, so components not reachable from vertex 0 are ignored.
- Marking grid cells visited too late (after popping) in the explicit-stack version, which pushes the same cell many times.
Interview tips
- Write the recursive version first for clarity, then mention the iterative alternative and why it matters for deep inputs.
- For cycle questions, ask whether the graph is directed before choosing between the parent check and three colors.
- When modifying the input grid to mark visited cells, say so and ask whether mutation is acceptable.
Real-world applications
- Maze generation (randomized DFS) and maze solving.
- Detecting deadlocks as cycles in a wait-for graph.
- Garbage collection mark phase: marking every object reachable from the roots.
- Paint-bucket fill and connected-region labeling in image processing.
- Dependency resolution and topological ordering in build tools.
- Backtracking search in puzzles, constraint solvers and game trees.
Practice problems
Test yourself
While running DFS on a directed graph you examine edge u → v and find that v is gray. What does this tell you?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.