DFS Parameters
December 01, 2026
Overview
Depth-first search (DFS) explores one branch of a search space before returning to explore other branches.
When implementing recursive DFS, one of the most important decisions is determining which arguments to pass to the recursive function.
For example:
def dfs(start):
...
def dfs(start, remaining):
...
def dfs(r, c, i):
...All three functions can perform depth-first search. However, each represents a different kind of search state.
The key idea is surprisingly simple:
The arguments passed into a recursive DFS function represent the state that must be communicated to the next recursive call.
That state may describe which candidates remain available, where we are in a grid, or how much of a constraint remains unsatisfied.
Other information may already be accessible from the enclosing function or derivable from the current path.
We will examine common DFS structures, how they construct different recursion trees, and how to determine which state should be passed explicitly.
First, Understand the State of a Recursive Call
Consider a problem where we need to select two numbers from [1, 2, 3, 4] without repetition.
Suppose we have already selected 2.
Current path: [2]
Eligible numbers: [3, 4]
Numbers required: 1The current path describes what we have selected. The eligible numbers describe what we can select next. The number required describes when the search should terminate.
We could pass all of that information explicitly:
dfs(start=3, remaining=1, path=[2])But if path is already maintained in the enclosing function and the required combination size is k, the remaining count can be derived:
remaining = k - len(path)A simpler recursive signature might therefore be:
dfs(start=3)This does not mean that the other state disappears. It simply means that we do not need to pass it as a separate argument.
DFS vs. Backtracking
DFS describes the order in which we explore a search space. Backtracking describes exploring choices and undoing them when returning to a previous decision point.
A typical backtracking pattern is:
path.append(candidate) # Choose
dfs(next_state) # Explore
path.pop() # Undo the choiceNot every DFS implementation requires undoing a choice. A flood-fill algorithm, for example, may permanently mark visited cells during the traversal.
1. dfs(start) — Enumerating Candidates
Common problems: Combinations, Subsets.
Suppose we want all combinations of k distinct numbers from 1 through n.
def combine(n, k):
resp = []
path = []
def dfs(start):
if len(path) == k:
resp.append(path[:])
return
remaining_needed = k - len(path)
for num in range(start, n - remaining_needed + 2):
path.append(num)
dfs(num + 1)
path.pop()
dfs(1)
return respHere, start represents the first eligible candidate at the current recursion level.
Because the numbers are considered in increasing order, the algorithm does not produce both [1, 2] and [2, 1].
Visualizing the Recursion Tree
For n = 4 and k = 2:
[] dfs(1)
/ | \
[1] dfs(2) [2] dfs(3) [3] dfs(4)
/ | \ / \ |
[1,2][1,3][1,4] [2,3][2,4] [3,4]The search does not select 4 at the root because doing so would leave no eligible second number.
Why num + 1 Instead of start + 1?
Consider this recursive call:
dfs(num + 1)If start = 1 but the loop selects 3, the next eligible candidate must be 4, not 2.
The recursive call advances beyond the selected candidate, not merely beyond the previous starting position.
Using dfs(start + 1) would allow invalid orderings and could even allow a previously selected value to be selected again.
Pruning Impossible Branches
The simpler loop is:
for num in range(start, n + 1):This is correct, but it can explore paths that cannot reach length k.
If we still need remaining_needed numbers, the largest eligible next selection is:
n - remaining_needed + 1Since Python excludes the upper bound of range(), the loop becomes:
for num in range(start, n - remaining_needed + 2):The pruning rule removes impossible branches without removing valid combinations.
We also do not need to pass n, k, or path because they are accessible from the enclosing function.
Depth can be derived in constant time using len(path).
2. dfs(i) — Include or Exclude
Common problems: Subsets, Subset Sum.
Instead of looping through eligible candidates, each recursive call decides what to do with exactly one input element.
def subsets(nums):
resp = []
path = []
def dfs(i):
if i == len(nums):
resp.append(path[:])
return
# Include
path.append(nums[i])
dfs(i + 1)
path.pop()
# Exclude
dfs(i + 1)
dfs(0)
return respFor nums = [1, 2]:
[] i=0
/ \
include 1 exclude 1
[1] i=1 [] i=1
/ \ / \
+2 -2 +2 -2
[1,2] [1] [2] []
i=2 i=2 i=2 i=2Every level processes exactly one element, whether it is included or excluded.
That is why both recursive calls use:
dfs(i + 1)Candidate Enumeration vs. Include/Exclude
We can also generate subsets using the previous dfs(start) structure:
def subsets(nums):
resp = []
path = []
def dfs(start):
resp.append(path[:])
for i in range(start, len(nums)):
path.append(nums[i])
dfs(i + 1)
path.pop()
dfs(0)
return respNotice that we record a result at every recursive call, not just at the maximum depth.
Every partial path is itself a valid subset.
For distinct inputs, both implementations generate the same subsets, although potentially in different orders.
| Aspect | Candidate Enumeration | Include/Exclude |
|---|---|---|
| Meaning of index | First eligible candidate | Current element being processed |
| Decisions per call | Zero or more candidate selections | Include or exclude one element |
| Meaning of depth | Number of selected elements | Number of processed elements |
| Recording subsets | Every call | Terminal calls |
| Recursion structure | Variable branching factor | Binary branching |
| Best fit | Directly building combinations | Explicit decisions about every input element |
For n distinct elements, unpruned candidate enumeration makes 2^n recursive calls, whereas include/exclude makes 2^(n+1) - 1.
Both have 2^n output subsets, and copying those subsets requires a total of Θ(n × 2ⁿ) time for n >= 1.
The different call counts do not imply a different asymptotic output-generation complexity.
3. dfs(start, remaining) — Maintaining a Constraint
Common problems: Combination Sum, Combination Sum II.
Sometimes knowing which candidates are available is not enough.
We also need to know how close the current path is to satisfying a constraint.
Suppose we want combinations of distinct, strictly positive candidate values that add up to a target. Each candidate may be selected repeatedly.
def combination_sum(nums, target):
resp = []
path = []
def dfs(start, remaining):
if remaining == 0:
resp.append(path[:])
return
if remaining < 0:
return
for i in range(start, len(nums)):
path.append(nums[i])
dfs(i, remaining - nums[i])
path.pop()
dfs(0, target)
return respFollowing One Recursive Branch
For nums = [2, 3, 6, 7] and target = 7:
[] dfs(0, 7) remaining = 7
|
| Select 2
v
[2] dfs(0, 5) remaining = 5
|
| Select 2 again
v
[2, 2] dfs(0, 3) remaining = 3
|
| Select 3
v
[2, 2, 3] dfs(1, 0) remaining = 0
Record resultThe other valid combination is [7].
The two recursive arguments have distinct responsibilities:
startcontrols which candidates remain eligible.remainingcontrols whether the target has been reached or exceeded.
Why Pass remaining Instead of Recalculating It?
We could derive it from the path:
remaining = target - sum(path)However, sum(path) traverses the selected values.
Passing an updated remaining target instead avoids that repeated traversal.
dfs(i, remaining - nums[i])Under the usual bounded-integer cost model, updating the remaining target takes constant time, while summing the path takes time proportional to its length.
A separate argument is not strictly necessary for correctness. It is useful for efficiency and clarity.
Why i Instead of i + 1?
Combination Sum allows the same candidate to be selected again, so we recurse with i.
| Recursive Call | Meaning | Effect |
|---|---|---|
dfs(i + 1, remaining - nums[i]) | Advance beyond the selected index | Each input position can be used at most once |
dfs(i, remaining - nums[i]) | Keep the selected index eligible | Allow repeated selections |
dfs(0, remaining - nums[i]) | Restart candidate selection | Allows different orderings of the same values |
Important Nuance: Candidate Reuse, Duplicates, and Pruning
Combination Sum II allows duplicate input values but restricts each input position to one use.
Advancing to i + 1 enforces the position restriction, but does not by itself prevent duplicate output combinations.
One common solution is to sort the input and skip equal sibling candidates:
nums = sorted(nums)
# Inside dfs(start, remaining):
for i in range(start, len(nums)):
if i > start and nums[i] == nums[i - 1]:
continue
if nums[i] > remaining:
break
path.append(nums[i])
dfs(i + 1, remaining - nums[i])
path.pop()The condition i > start matters.
It skips equivalent choices at the same recursion level, without preventing equal values at different levels when they come from different input positions.
The early break is valid because the candidates are sorted and strictly positive.
With negative values, exceeding the target may not mean a branch is impossible. With unlimited reuse of zero or negative values, additional termination constraints may also be necessary.
4. dfs() — State Maintained in the Enclosing Scope
Common problem: Permutations.
Unlike combinations, permutations care about the order of the selected elements.
Every unused input position is a valid candidate at each recursion level.
def permute(nums):
resp = []
path = []
used = set()
def dfs():
if len(path) == len(nums):
resp.append(path[:])
return
for i in range(len(nums)):
if i in used:
continue
path.append(nums[i])
used.add(i)
dfs()
path.pop()
used.remove(i)
dfs()
return respFor nums = [1, 2, 3], the first two levels are:
[]
/ | \
[1] [2] [3]
/ \ / \ / \
[1,2][1,3][2,1][2,3][3,1][3,2]
| | | | | |
Continue until all positions are usedThere is no need for a starting index because the search must be able to return to earlier unused positions.
Restricting subsequent selections to larger indices would eliminate valid permutations such as [3, 2, 1].
All necessary changing state is maintained in path and used. Both must be restored after each branch.
Important Nuance: No Arguments Does Not Mean No State
The signature dfs() does not tell us everything about the recursive call.
Each invocation observes the current contents of path and used in the enclosing scope.
For this reason, calling dfs() twice without changing or restoring the appropriate state would not necessarily represent two different branches.
The implementation assumes distinct input values if we want unique value permutations. Tracking used indices correctly distinguishes repeated input positions, but equal values may still produce duplicate output permutations.
5. dfs(r, c) — Navigating a Grid
Common problems: Number of Islands, Flood Fill, Max Area of Island.
Here, the recursive arguments describe a location in a two-dimensional grid rather than a position in an ordered candidate list.
def num_islands(grid):
if not grid or not grid[0]:
return 0
m, n = len(grid), len(grid[0])
def dfs(r, c):
if not (0 <= r < m and 0 <= c < n):
return
if grid[r][c] != "1":
return
grid[r][c] = "0"
dfs(r + 1, c)
dfs(r - 1, c)
dfs(r, c + 1)
dfs(r, c - 1)
count = 0
for r in range(m):
for c in range(n):
if grid[r][c] == "1":
count += 1
dfs(r, c)
return countVisualizing the Neighbor Relationships
(r-1, c)
|
(r, c-1) ---- (r, c) ---- (r, c+1)
|
(r+1, c)The grid represents both the input and the visited state in this implementation.
Changing a land cell to water prevents the search from repeatedly visiting the same cell, including immediately returning to its parent.
For example:
Before DFS from (0, 0) After DFS from (0, 0)
1 1 0 0 0 0 0 0
1 0 0 1 0 0 0 1
0 0 1 1 0 0 1 1The first connected component has been marked. The outer loop later discovers the remaining component.
Mutating the Input vs. Maintaining a Visited Set
| Aspect | Mutate the Grid | Separate Visited Set |
|---|---|---|
| Original input | Modified | Preserved |
| Additional visited storage | No separate structure | Up to O(m × n) entries |
| Recursion stack | Still required | Still required |
| Reuse of input | Requires a copy or reconstruction | Original values remain available |
| Best fit | Disposable, mutable input | Read-only or reusable input |
The algorithm deliberately does not restore visited cells.
We want subsequent DFS calls, including those made by the outer loop, to know that those cells have already been explored.
Assuming a rectangular grid, the traversal takes O(m × n) time.
Its recursive call stack can also reach O(m × n) in the worst case, even when no separate visited set is used.
6. dfs(r, c, i) — Navigating a Grid While Tracking Progress
Common problem: Word Search.
Suppose we want to determine whether a word can be constructed by visiting horizontally or vertically adjacent cells, without reusing a cell on the same path.
We need the current position and the character we expect to match next.
def exist(board, word):
if not word:
return True
if not board or not board[0]:
return False
m, n = len(board), len(board[0])
visited = set()
def dfs(r, c, i):
if not (0 <= r < m and 0 <= c < n):
return False
if (r, c) in visited or board[r][c] != word[i]:
return False
if i == len(word) - 1:
return True
visited.add((r, c))
found = (
dfs(r + 1, c, i + 1) or
dfs(r - 1, c, i + 1) or
dfs(r, c + 1, i + 1) or
dfs(r, c - 1, i + 1)
)
visited.remove((r, c))
return found
return any(
dfs(r, c, 0)
for r in range(m)
for c in range(n)
)The three arguments each have a distinct responsibility:
r: current row.c: current column.i: index of the character we need to match.
For word = "CAT":
c=0 c=1 c=2
r=0 C -> A X
|
v
r=1 X T X
dfs(0, 0, 0) Match C
|
dfs(0, 1, 1) Match A
|
dfs(1, 1, 2) Match T; return TrueThe coordinates can move in different directions, but the word index always increases.
We do not need a separate path list because the function only returns whether a matching path exists.
We can also temporarily mark a cell in the board itself, as in the following alternative:
# After the bounds, character and terminal checks:
char = board[r][c]
board[r][c] = "#"
found = (
dfs(r + 1, c, i + 1) or
dfs(r - 1, c, i + 1) or
dfs(r, c + 1, i + 1) or
dfs(r, c - 1, i + 1)
)
board[r][c] = char
return foundIn this variant, remove the separate visited set and its checks, and use a marker that cannot occur in any valid board or word character, such as # when the alphabet consists only of letters.
Permanent vs. Path-Specific Visited State
| Aspect | Number of Islands | Word Search |
|---|---|---|
| Search objective | Explore an entire connected component | Find a path matching a word |
| Visited state | Shared across the traversal | Specific to the active path |
| Revisit after backtracking? | No | Yes, through another path |
| Restore visited state? | No | Yes |
| Typical return value | None, or a component aggregate | Boolean |
Two Word Search calls can arrive at the same cell and word index through different paths.
Their previously visited cells can differ, which changes the legal future moves.
This is why simply memoizing (r, c, i) is not generally correct: it ignores information that affects the answer.
7. dfs(node) — Traversing a Tree or Graph
Common problems: Maximum Depth, Invert Binary Tree, Same Tree.
When traversing a tree, the node itself represents the current location. Its child references determine the next candidates.
def max_depth(root):
def dfs(node):
if node is None:
return 0
return 1 + max(
dfs(node.left),
dfs(node.right)
)
return dfs(root)Consider this tree:
A returns 3
/ \
B C returns 2, 1
/
D returns 1The current depth does not need to be passed explicitly because each call returns the height of the subtree rooted at its node.
This is a bottom-up calculation: child results are combined by the parent.
An alternative is to pass the current depth explicitly:
def max_depth(root):
best = 0
def dfs(node, depth):
nonlocal best
if node is None:
return
best = max(best, depth)
dfs(node.left, depth + 1)
dfs(node.right, depth + 1)
dfs(root, 1)
return bestThis is a top-down calculation: each call receives information accumulated from its ancestors.
| Aspect | Bottom-Up | Top-Down |
|---|---|---|
| Signature | dfs(node) | dfs(node, depth) |
| Information passed down | Current node | Current node and root-relative depth |
| Information returned | Height of the subtree | No value in this implementation |
| Result management | Combine child results | Update a shared maximum |
| Time complexity | O(N) | O(N) |
| Auxiliary stack space | O(h) | O(h) |
Here, N is the number of nodes and h is the height of the tree.
Both approaches are correct, but they represent progress differently.
When Do We Need an Additional Argument?
Consider Path Sum. We want to know whether a root-to-leaf path sums to a target.
def has_path_sum(root, target):
def dfs(node, remaining):
if node is None:
return False
remaining -= node.val
if node.left is None and node.right is None:
return remaining == 0
return (
dfs(node.left, remaining) or
dfs(node.right, remaining)
)
return dfs(root, target)The node determines where we are, while the remaining target describes the constraint accumulated along the path.
Notice that reaching zero does not immediately guarantee success.
The problem requires a root-to-leaf path, so the condition must be checked at a leaf.
We also cannot generally prune a branch just because remaining becomes negative: later nodes might have negative values.
Important Nuance: Trees vs. General Graphs
A proper tree has no cycles or shared descendants.
In a general graph, however, a node may lead back to an already visited node.
def traverse(graph, start):
visited = set()
def dfs(node):
if node in visited:
return
visited.add(node)
for neighbor in graph.get(node, []):
dfs(neighbor)
dfs(start)
return visitedThis uses the same signature, dfs(node), but requires additional visited state for cycle prevention and to avoid repeatedly exploring shared descendants.
For ordinary reachability in an adjacency-list graph, the traversal takes O(V + E) time in the worst case.
Enumerating all simple paths is a different problem and generally requires path-specific visited state instead.
How to Determine Which Arguments to Pass
There are four useful categories of state to consider.
| State | Examples | How to Maintain It |
|---|---|---|
| Constant state | n, k, target, nums | Enclosing scope if unchanged |
| Position state | i, start, r, c, node | Usually recursive arguments |
| Accumulated state | remaining, total, depth | Pass explicitly, derive, or return an aggregate |
| Mutable search state | path, used, visited | Shared state with restoration when branch-specific, or separate per-call state |
Explicit Arguments vs. Derived State
Consider our original combinations solution.
We could use:
def dfs(start, remaining):
...Or even:
def dfs(start, depth, path):
...But because the path is already available, these quantities can be calculated directly:
depth = len(path)
remaining = k - len(path)Both calculations take constant time.
In this particular implementation, passing them separately would introduce redundant state that must remain synchronized with path.
Contrast that with Combination Sum:
remaining = target - sum(path)This calculation requires traversing the path.
Passing remaining avoids recomputing information we already know from the previous call.
Shared Mutable State vs. Copying State
There are also two common ways to manage the path itself.
Shared mutable path:
path.append(nums[i])
dfs(i + 1)
path.pop()Separate path for each recursive call:
dfs(i + 1, path + [nums[i]])| Aspect | Shared Mutable Path | Separate Path per Call |
|---|---|---|
| Passing path | Often captured in enclosing scope | Explicit argument |
| Extending path | Append and later pop | Allocate and copy the list |
| Branch isolation | Requires correct restoration | Each branch receives its own list |
| Cost of extending path | Amortized O(1) | O(d), where d is path length |
| Peak path storage along depth D | O(D) | Up to O(D²) for list references |
| Recording a result | Usually copy the path | Can store the path if never modified later |
| Best fit | Allocation-conscious backtracking | Simpler ownership and branch isolation |
These costs exclude the output and other search structures.
The copied lists contain references to the original elements; they are not deep copies.
Importantly, passing a Python list as an argument does not automatically copy it.
dfs(i + 1, path)This still shares the same mutable list.
The isolation above comes from constructing path + [nums[i]].
Additional Arguments Are Not Always Necessary for Additional Information
Recursive arguments describe information flowing from a parent call to a child call. Return values describe information flowing back.
For Maximum Depth, child calls return a subtree height.
For Max Area of Island, child calls can return an area to add together.
For Word Search, child calls return a Boolean and the parent can short-circuit when a match is found.
Before introducing another argument, consider whether the information belongs in the input state or in the result returned by the recursive call.
Recursive Arguments and Memoization
Memoization stores a previously computed result so an equivalent future call can reuse it.
Consider Subset Sum with nonnegative input values and a nonnegative target:
from functools import cache
def subset_sum(nums, target):
@cache
def dfs(i, remaining):
if remaining == 0:
return True
if i == len(nums) or remaining < 0:
return False
return (
dfs(i + 1, remaining - nums[i]) or
dfs(i + 1, remaining)
)
return dfs(0, target)For this decision problem, i and remaining fully determine the remaining search, given the fixed input.
The exact previously selected elements do not affect which elements are still eligible or what total we need.
There are at most O(n × (target + 1)) reachable cached states for n >= 1, giving a pseudo-polynomial bound under the usual integer cost model.
The recursion stack can still grow to O(n).
However, not every DFS can be memoized using only its explicit arguments.
| DFS State | Sufficient Cache Key? | Reason |
|---|---|---|
Subset Sum: (i, remaining) | Yes, for existence | Fixed suffix and remaining target determine the answer |
Word Search: (r, c, i) | No, in general | Previously visited cells affect future choices |
Permutations: () | No | Current path and used positions affect the search |
Tree height: node | Yes, for an unchanged tree | Subtree height depends only on that subtree |
A sufficient cache key must capture all state that affects the returned result.
Moreover, caching a function that appends to a shared result list may suppress required side effects, even if the function arguments repeat.
Summary of Common DFS Structures
| DFS Signature | Explicit State | Example |
|---|---|---|
dfs() | None | Permutations |
dfs(start) | First eligible candidate | Combinations |
dfs(i) | Current input element | Subsets (include/exclude) |
dfs(start, remaining) | Candidate boundary and constraint | Combination Sum |
dfs(i, total) | Current element and accumulated value | Subset Sum |
dfs(r) | Current row | N-Queens |
dfs(r, c) | Grid position | Number of Islands |
dfs(r, c, i) | Grid position and sequence progress | Word Search |
dfs(node) | Current node | Maximum Depth |
dfs(node, remaining) | Current node and constraint | Path Sum |
For N-Queens, for example, the row can advance with dfs(r + 1) while occupied columns and diagonals are maintained separately.
The row alone does not describe all occupied positions.
These signatures are conventions rather than strict requirements. The same problem can often be solved with several different DFS structures.
Common Pitfalls and Trade-offs
| Pitfall | Why It Happens | Better Approach |
|---|---|---|
Using start + 1 instead of i + 1 | Confusing the previous boundary with the selected candidate | Advance from the selected index when reuse is forbidden |
Using i + 1 when reuse is required | Applying the combinations pattern mechanically | Keep i eligible for unlimited positive-candidate reuse |
| Passing redundant arguments | Treating all state as explicit recursive input | Derive inexpensive quantities from existing state |
| Recalculating expensive state | Avoiding arguments without considering cost | Maintain running totals or remaining constraints incrementally |
| Forgetting to restore shared state | Recursive branches mutate the same objects | Undo branch-specific choices before returning |
Appending path directly | Python stores a reference to the same mutable list | Append path[:] when reusing the list |
| Restoring globally visited cells | Treating ordinary traversal as path enumeration | Keep globally explored cells marked when appropriate |
| Pruning without validating assumptions | Applying positive-number logic to arbitrary values | Verify that pruning cannot remove a valid solution |
| Memoizing incomplete state | Assuming the function signature contains all relevant information | Include all state affecting the result in the cache key |
| Ignoring recursion depth | Focusing only on output size or traversal complexity | Consider worst-case stack depth and iterative DFS |
In Python, a deep recursive DFS can exceed the interpreter's recursion limit.
For potentially deep trees, graphs, or large connected grids, an explicit stack may be a better choice.
Backtracking can also be implemented iteratively, but the explicit stack must preserve the necessary decision and restoration state.
Conclusion
The arguments passed to a recursive DFS function describe how we move from one search state to the next.
A combinations search advances beyond the selected candidate.
An include/exclude search advances beyond the element it just processed.
A constraint-based search also tracks how much of the target remains.
A grid search tracks coordinates, and a tree search may need only the current node.
However, the function signature is only part of the complete search state.
Some information is constant, some is derived, some is maintained in shared mutable objects, and some is computed through recursive return values.
The general principle is to pass the minimum useful explicit state needed for the next recursive decision, without introducing unnecessary computation or cumbersome state management.
Understanding what each argument represents is more valuable than memorizing a collection of DFS templates.
Key Takeaways
startrepresents the first eligible candidate;iin an include/exclude search represents the current input element.- Advance from the selected index using
i + 1when a position cannot be reused, oriwhen reuse is allowed. - Additional arguments such as
remainingcan avoid repeated computation. - A function with no arguments can still depend on changing state in its enclosing scope.
- Backtracking requires restoring branch-specific state, not necessarily all visited state.
- The same problem can be solved with different recursion trees and different argument signatures.
- Return values can compute information bottom-up instead of passing it down as an argument.
- Memoization is correct only when its key captures all relevant state and caching is compatible with the function's behavior.
References and Practice Problems
- Python Documentation — More on Lists
- Python Documentation — functools.cache
- Combinations
- Subsets
- Combination Sum
- Combination Sum II
- Permutations
- N-Queens
- Number of Islands
- Word Search
- Maximum Depth of Binary Tree
- Path Sum
- Partition Equal Subset Sum

