Converting a recursive Depth-First Search (DFS) to an iterative version involves replacing the inherent function call stack used in recursion with an explicit stack data structure. This helps avoid potential stack overflow errors and can provide better control over the traversal process.
How to Convert Recursive DFS to Iterative DFS in Java:
- Understand the Recursive DFS Structure A typical recursive DFS looks like this:
void dfs(int node, boolean[] visited, List<List<Integer>> graph) {
visited[node] = true;
// Process the node here (e.g., print or accumulate)
for (int neighbor : graph.get(node)) {
if (!visited[neighbor]) {
dfs(neighbor, visited, graph);
}
}
}
Replace Recursion with an Explicit Stack
Use aStack<Integer>
to manually manage nodes to visit.Standard Iterative DFS Algorithm:
void iterativeDFS(int start, List<List<Integer>> graph) {
boolean[] visited = new boolean[graph.size()];
Stack<Integer> stack = new Stack<>();
stack.push(start);
while (!stack.isEmpty()) {
int node = stack.pop();
if (!visited[node]) {
visited[node] = true;
// Process the node here (e.g., print or accumulate)
System.out.println("Visited node: " + node);
// Push neighbors to stack (usually in reverse order to maintain traversal order)
List<Integer> neighbors = graph.get(node);
for (int i = neighbors.size() - 1; i >= 0; i--) {
int neighbor = neighbors.get(i);
if (!visited[neighbor]) {
stack.push(neighbor);
}
}
}
}
}
Key Points:
- Stack Usage: Instead of recursive calls, the stack stores nodes waiting to be visited.
- Visited Check: You must mark nodes as visited after popping them to avoid revisiting.
- Ordering Neighbors: To maintain the same node visitation order as recursive DFS, neighbors should often be pushed onto the stack in reverse order.
-
Graph Representation: Here, the graph is represented as an adjacency list (
List<List<Integer>>
).
Has This Been Seen in Practice?
Yes, iterative DFS is a common technique in professional software development, especially:
- When the graph is very deep or large, and recursion depth could cause stack overflow.
- In coding interviews, iterative DFS is frequently requested as an alternative to recursion.
- In system-level applications where manual stack management improves performance or control.
This iterative approach is widely used and well-understood as a key graph traversal strategy in Java and other languages.