Depth-First Search (DFS) Template & Important Notes
🌊 Core Intuition of DFS
DFS = go as deep as possible first, then backtrack.
It keeps following one path until it hits a stopping condition, then returns and explores the next path.
🧠 Universal DFS Mental Model
DFS always follows this skeleton:
1. Base condition
2. Mark visited
3. DFS on neighborsdef dfs(node):
# 1. Base condition
if invalid(node) or node in visited:
return
# 2. Mark visited
visited.add(node)
# 3. DFS neighbors
for neighbor in get_neighbors(node):
dfs(neighbor)✅ What’s Always the Same in DFS
| Concept | Meaning |
|---|---|
| Base condition | When to stop |
| Visited | Prevent revisiting/cycles |
| Neighbors | Where DFS can go next |
| Recursion | Explore deeper before coming back |
| Backtracking | Return when no more valid paths |
🔍 DFS Thinking Template
For any DFS problem, ask:
1. What is a node?
2. What makes a node invalid?
3. How do I mark it visited?
4. Who are its neighbors?
5. What does one DFS call completely explore?
6. What am I trying to count/find/build?🧩 Easy Way to Remember
Think of DFS as:
Is this node part of what I’m exploring?
If no:
returnIf yes:
mark visited
dfs(neighbor1)
dfs(neighbor2)
dfs(neighbor3)
...Shortcut:
Stop → Visit → Explore
🛠️ Helper Function You Can Customize
def get_neighbors(node):
# Grid: return 4 or 8 directions
# Graph: return graph[node]
# Tree: return node.left / node.right
pass🔍 When Do You Need visited?
| Structure | Is visited needed? | Why? |
|---|---|---|
| Graph | ✅ Yes | Can contain cycles |
| Grid | ✅ Yes | Can revisit cells |
| Tree | ❌ Usually no | No cycles if traversing downward |
| Modified grid | ❌ Maybe no | Grid itself can mark visited |
| Backtracking path | ✅ Path set | Avoid using same node in current path |
Rule of thumb:
If there’s a chance of reaching the same node again, use visited.
✅ You Can Skip visited If...
| ✅ You can skip visited when... | ❌ You need visited when... |
|---|---|
| You modify the input to mark progress | Input must remain unchanged |
| The structure has no cycles, like a tree | Graph/grid can loop |
| Each node is naturally visited once | Multiple paths can reach same node |
| State itself marks progress | State must be tracked separately |
Example:
grid[i][j] = "0"can replace:
visited.add((i,j))in problems like Number of Islands.
🌍 DFS Template — Grid With visited
visited = set()
directions = [(1,0), (-1,0), (0,1), (0,-1)]
def dfs(i, j):
if (
not 0 <= i < rows
or not 0 <= j < cols
or grid[i][j] is invalid
or (i,j) in visited
):
return
visited.add((i,j))
for di, dj in directions:
dfs(i+di, j+dj)Mental model:
Is this cell valid and unvisited? If yes, visit it and explore every direction.
🌍 DFS Template — Grid Without visited
Use this when you can modify the grid directly.
directions = [(1,0), (-1,0), (0,1), (0,-1)]
def dfs(i, j):
if (
not 0 <= i < rows
or not 0 <= j < cols
or grid[i][j] is invalid
):
return
grid[i][j] = visited_value
for di, dj in directions:
dfs(i+di, j+dj)Example:
grid[i][j] = "0"means:
This land is now visited.
🔗 DFS Template — Graph Traversal
visited = set()
def dfs(node):
if node in visited:
return
visited.add(node)
for neighbor in graph[node]:
dfs(neighbor)Use this when the graph is given as:
graph = {
1: [2,3],
2: [1,4],
3: [1],
4: [2]
}🌳 DFS Template — Binary Tree
For trees, you usually do not need visited.
def dfs(node):
if not node:
return
# process node
dfs(node.left)
dfs(node.right)Why no visited?
Because in normal binary tree traversal, children do not point back to parents.
🧮 DFS Template — Connected Components
Use this when the question asks:
- number of islands
- number of provinces
- connected components
- groups/clusters
visited = set()
def dfs(node):
if node in visited:
return
visited.add(node)
for neighbor in get_neighbors(node):
dfs(neighbor)
count = 0
for node in all_nodes:
if node is valid and node not in visited:
count += 1
dfs(node)
return countMental model:
Every time I find an unvisited valid node, I found a new component.
One DFS explores that whole component.
🏝️ Example: Number of Islands
For Number of Islands:
Node → cell (i, j)
Valid node → grid[i][j] == "1"
Neighbors → up/down/left/right
Visited → set() or mark grid as "0"
One DFS explores → one entire island
Counting → number of islandsDFS question:
Is this cell part of the current island?
If yes, mark visited and explore neighbors.
🧠 DFS vs BFS
| DFS | BFS |
|---|---|
| Uses recursion/stack | Uses queue |
| Goes deep first | Goes level by level |
| Good for components, paths, backtracking | Good for shortest path/levels |
| “Explore this whole region” | “Explore closest nodes first” |
🔑 Key Takeaway
DFS is just:
Base condition
↓
Mark visited
↓
DFS neighborsThe main question is:
What does one DFS call completely explore?
Examples:
Number of Islands → one island
Number of Provinces → one province
Flood Fill → one color region
Max Area of Island → one island and its area
Tree DFS → one subtreeOnce you know what one DFS explores, the rest becomes much easier.

