Depth-first search, components & cycles
Use DFS to count components, detect cycles and flood-fill grids.
By Invicly Tech, , in Data Structures & Algorithms. About 12 minutes to read.
In short
Depth-first search follows one path as far as it can before backtracking. It is the basis for counting connected components, detecting cycles, flood fill and topological sorting. It can be written recursively or with an explicit stack.
Explained simply
Depth-first search, or DFS, explores a graph like a person in a cave with a ball of string. It takes one tunnel and keeps going until it hits a dead end. Then it walks back to the last junction and tries the next tunnel.
DFS needs a memory of where it has been, the visited set, so it never enters the same room twice. It also needs a way to go back. The simplest way is recursion: the function calls itself for each new neighbour, and returning from the call means walking back.
DFS does not find shortest paths. Its strength is answering structure questions: Which vertices can I reach? How many separate groups are there? Is there a loop? It is also the engine behind flood fill in paint programs and island counting in grids.
Like BFS, DFS looks at each vertex and each edge once, so it runs in O(V + E) time.
Press Play on a diagram to walk through it one step at a time.
- Step 1Scan cells
Row by row.
- Step 2Find land
Unvisited '1' starts a new island.
- Step 3DFS flood
Mark all connected land visited.
- Step 4Count
Increment once per DFS start.
- Stack or recursion
- Goes deep first, then backtracks
- Cycles, components, topological order
- Memory: depth of the path
- Queue (deque)
- Explores layer by layer
- Fewest-edges shortest paths
- Memory: width of a layer
In depth
Recursive or iterative: the Python stack limit
Recursive DFS is short and clear, but every call uses a stack frame. CPython limits recursion depth to 1,000 by default, so a path of 5,000 vertices, or a 100 x 100 grid shaped like a snake, raises RecursionError. You can call sys.setrecursionlimit with a bigger number, but very deep recursion can still crash the interpreter, because the real C stack runs out.
The safe choice for large inputs is an explicit stack, a Python list used with append() and pop(). For reachability and counting components, a simple version works: pop a vertex, then push each unvisited neighbour and mark it. The visiting order differs slightly from recursive DFS, but every reachable vertex is found exactly once.
When you need the exact recursive order, such as finish times for topological sort, push (vertex, iterator over neighbours) pairs instead. Each step advances the top iterator, and a vertex is finished when its iterator runs out.
- Default recursion limit: sys.getrecursionlimit() returns 1000
- A 1000 x 1000 grid can need up to 1,000,000 levels
- Simple stack DFS is enough for reachability and components
Connected components
A connected component is a group of vertices that can all reach each other, and cannot reach anything outside the group. To count components in an undirected graph, loop over every vertex. If it is not visited yet, you have found a new component: add one to the count and run a DFS from it to mark the whole group. Every vertex is visited once overall, so the total is still O(V + E), not O(V x (V + E)).
You can label each vertex with its component number instead of just counting. Then "are a and b connected?" becomes an O(1) check: comp[a] == comp[b].
In directed graphs the idea splits in two. Weakly connected ignores edge direction. Strongly connected means every vertex can reach every other one following the arrows. Strongly connected components are found with Tarjan's or Kosaraju's algorithm, both O(V + E).
Three colours for cycles in directed graphs
In a directed graph, reaching an already visited vertex does not prove a cycle. In A to B, A to C, B to C, the vertex C is reached twice, yet there is no loop. What matters is whether the vertex is still on the current path.
So DFS gives every vertex one of three colours. White: not visited yet. Grey: entered, and its DFS call is still running, so it is on the current path. Black: finished, all its descendants explored. When you follow an edge u to v and v is grey, you have found a back edge, and that closes a cycle. An edge to a black vertex is safe.
For undirected graphs, two states are enough, but you must ignore the edge back to the parent you just came from. Otherwise every edge looks like a tiny cycle. Union-find is another simple way to detect cycles in undirected graphs.
- 1Enter u
Colour u grey: it is on the path
- 2Edge to white v
Recurse into v
- 3Edge to grey v
Back edge: cycle found
- 4Edge to black v
Already finished: ignore
- 5Leave u
Colour u black: finished
Discovery times, finish times and edge types
If you write down a counter value when DFS enters a vertex (discovery time) and when it leaves (finish time), the intervals nest like brackets. If v is discovered inside u's call, v also finishes before u. This is called the parenthesis property.
These times let you classify every edge in a directed graph. A tree edge leads to a new white vertex. A back edge goes to a grey ancestor and means a cycle. A forward edge jumps to an already finished descendant. A cross edge goes to a finished vertex in another branch. In an undirected graph only tree edges and back edges can appear.
Finish times are the key to topological sort: listing vertices by decreasing finish time puts every edge pointing forward. The same times power Tarjan's algorithms for bridges, articulation points and strongly connected components.
- Tree edge
- v was white
- Builds the DFS tree
- Back edge
- v is grey (an ancestor)
- Means a cycle
- Forward edge
- v is a finished descendant
- Shortcut down the tree
- Cross edge
- v is finished, other branch
- No cycle
Flood fill on grids
Flood fill is DFS on a grid: start at one cell and mark every connected cell with the same value. Paint bucket tools, island counting and "surrounded regions" puzzles all use it. The run is O(R x C) because each cell is marked once.
You can mark visited cells in two ways. Changing the grid itself, for example setting '1' to '0', needs no extra memory but destroys the input; copy it first if the caller still needs it. A separate visited set or 2D boolean list keeps the input intact.
Decide on 4-connectivity (up, down, left, right) or 8-connectivity (diagonals too) from the problem statement. Two diagonal land cells are one island under 8-connectivity and two islands under 4. On big grids, prefer an explicit stack or BFS, because a single snake-shaped island can be deeper than Python's recursion limit.
Learn it in 4 short steps
About 45m each. Track them with a timer in your plan.
- 1Implement recursive and iterative DFS~45m
- 2Count connected components~45m
- 3Detect cycles with three-colour marking~45m
- 4Flood-fill islands in a grid~45m
Key points
- Time O(V + E); grids are O(rows x cols).
- Directed cycle detection uses three states: unvisited, in progress, done.
- An edge to an in-progress vertex is a back edge, which means a cycle.
- Use an explicit stack for very deep graphs in Python.
Key terms
Tap a card to flip it. 0/4 known
Examples
def num_islands(grid): # O(rows * cols)
rows, cols = len(grid), len(grid[0])
def sink(r, c):
if 0 <= r < rows and 0 <= c < cols and grid[r][c] == '1':
grid[r][c] = '0'
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
sink(r + dr, c + dc)
count = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] == '1':
sink(r, c); count += 1
return countCounting friend groups with an iterative DFS
There are n people and a list of friendships. Step 1: build an undirected adjacency list. Step 2: loop over every person; each one not yet seen starts a new group, so count += 1. Step 3: run a stack-based DFS from that person and mark everyone reachable. For n = 5 and edges [[0, 1], [1, 2], [3, 4]], the starts are 0 and 3, so the answer is 2. No recursion is used, so a long chain of a million people is fine.
def count_groups(n, edges):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v); adj[v].append(u)
seen, count = [False] * n, 0
for s in range(n):
if seen[s]:
continue
count += 1
seen[s], stack = True, [s]
while stack:
u = stack.pop()
for v in adj[u]:
if not seen[v]:
seen[v] = True; stack.append(v)
return countFinding a cycle in task dependencies
Tasks 0, 1, 2 have edges 0 to 1, 1 to 2 and 2 to 0. Step 1: visit 0 and colour it grey. Step 2: follow 0 to 1, colour 1 grey; follow 1 to 2, colour 2 grey. Step 3: follow 2 to 0 and see that 0 is grey, so it is still on the current path: a back edge, so a cycle. Remove the edge 2 to 0 and every vertex ends black with no grey hit, so there is no cycle.
def has_cycle(n, edges):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
WHITE, GREY, BLACK = 0, 1, 2
colour = [WHITE] * n
def visit(u):
colour[u] = GREY
for v in adj[u]:
if colour[v] == GREY or (colour[v] == WHITE and visit(v)):
return True
colour[u] = BLACK
return False
return any(colour[u] == WHITE and visit(u) for u in range(n))Quick reference
- DFS is O(V + E) time; O(V) space for visited plus the stack
- Python's default recursion limit is 1000; use an explicit stack for deep graphs
- Components: count how many times you start a new DFS from an unvisited vertex
- Directed cycle: an edge to a grey (in-progress) vertex
- Undirected cycle: a visited neighbour that is not the parent
- Reverse of DFS finish order is a topological order of a DAG
- Flood fill: 4 directions or 8 directions changes the answer
Common mistakes
- Using an undirected visited check for directed cycle detection.
- Recursion depth errors on large grids; raise the limit or go iterative.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write reachable(adj, start) that returns the set of all vertices reachable from start, using an explicit stack.
- Exercise 2medium
Return the area of the largest island in a grid of 0s and 1s (4-direction). Use an explicit stack, not recursion.
- Exercise 3hard
Detect whether an undirected graph with n vertices has a cycle, using iterative DFS that tracks each vertex's parent.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Does DFS find the shortest path?
- No. DFS finds some path, often a long one. Use BFS for the fewest edges or Dijkstra for weighted graphs.
- How do I avoid RecursionError in Python DFS?
- Rewrite the DFS with an explicit list as a stack. Raising the limit with sys.setrecursionlimit helps a little, but very deep recursion can still crash the interpreter.
- What is the time complexity of DFS?
- O(V + E) with an adjacency list, because each vertex is visited once and each edge is examined once per direction. On a grid it is O(rows x cols).