Search
⌘K
Get Premium
Types of DFS
There are a few common "types" of depth-first search problems you'll encounter in coding interviews. Understanding these patterns will help you quickly recognize and solve similar problems.
Connected Components
The Problem: Given a 2D grid where 1 represents land and 0 represents water, count the number of distinct islands. An island is a group of 1s connected horizontally or vertically.
Example Input:
[0, 1, 0, 0, 0, 0]
[0, 1, 1, 0, 1, 0]
[0, 0, 0, 1, 1, 0]
[1, 1, 0, 0, 0, 1]
[1, 1, 0, 0, 0, 1]Expected Output: 4 (there are 4 separate islands)
How it works:
- We iterate through every cell in the grid
- When we find an unvisited 1, we've discovered a new island—increment the count
- We then use DFS to "flood fill" the entire island, marking all connected 1s as visited (by setting them to 0)
- After DFS returns, that island is fully explored and won't be counted again
What to watch for in the animation:
- Notice how we scan the grid from top-left to bottom-right
- When we find a 1, we start a DFS that "floods" the entire island, marking all connected cells
- The count variable increments each time we find an unvisited 1 (the start of a new island)
- Watch how the DFS explores deeply in one direction before backtracking
Visualization
Python
Count islands using DFS
0 / 59
Key insight: The outer loop finds new islands, and the DFS "consumes" each island so we don't count the same island twice.
Boundary DFS
The Problem: Given a 2D grid, find all 1s that are connected to the boundary of the matrix. This is a key step in solving problems like "Surrounded Regions" where you need to identify cells that cannot be captured because they're connected to the edge.
Example Input:
[0, 1, 0, 0, 1, 0]
[0, 1, 1, 0, 1, 0]
[0, 0, 1, 0, 1, 0]
[0, 1, 0, 0, 1, 1]
[0, 1, 1, 0, 1, 1]
[1, 0, 0, 0, 0, 0]How it works:
- Instead of scanning every cell, we only start DFS from cells on the boundary (edges) of the grid
- We iterate through the first and last rows, and the first and last columns
- For each boundary cell that contains a 1, we run DFS to mark all connected cells
- After this process, any 1 that was visited is connected to the boundary; any unvisited 1 is "surrounded"
What to watch for in the animation:
- Notice how DFS starts from cells on the edges of the matrix (not from the top-left corner)
- The algorithm only explores cells that are connected to the boundary
- Any 1 that gets visited is "safe" because it touches the edge
- Cells in the middle that aren't reached would be "surrounded"
Visualization
Python
Boundary DFS - find cells connected to edge
0 / 220
Key insight: Instead of checking if each cell is surrounded (hard), we flip the problem—find all cells that are NOT surrounded by starting from the boundary and working inward.
Mark as read
Your account is free and you can post anonymously if you choose.