Non-recursive depth first search algorithm
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction to Non-recursive Depth First Search (DFS) Algorithm
Depth First Search (DFS) is a fundamental graph traversal technique influential in both theoretical and practical aspects of computer science. Typically, DFS uses recursion, which leverages the function call stack. Non-recursive DFS, however, implements the DFS logic iteratively using an explicit stack data structure, thereby avoiding the limitations of recursion, such as stack overflow for deep recursions.
Understanding Graphs
Before delving into DFS, it's essential to understand graphs:
- Graph: A collection of nodes (vertices) and edges (connections between nodes).
- Undirected Graph: Edges lack direction; (A, B) implies (B, A).
- Directed Graph: Edges have direction; (A, B) does not imply (B, A).
- Cyclic Graphs: Graphs containing cycles.
- Acyclic Graphs: Graphs without any cycles.
Graphs can be represented using adjacency lists or matrices. The choice of representation affects the DFS implementation.
Algorithm of Non-recursive DFS
The primary mechanism to solve non-recursive DFS involves using an explicit stack to simulate the call stack of recursion.
Steps of Non-recursive DFS
- Initialization:
- Start by selecting a node (arbitrary or specified as the root node).
- Initialize an empty stack and push the starting node onto it.
- Maintain a set (or similar data structure) to record visited nodes.
- Traversal:
- While the stack is not empty:
- Pop the top node from the stack and check if it is visited.
- If not visited, mark as visited and process it.
- Push all adjacent unvisited nodes into the stack.
- Termination:
- The algorithm terminates when the stack becomes empty, indicating all reachable nodes are visited.
Pseudocode Example
Practical Example
Consider a simple undirected graph:
Starting DFS from vertex A using a non-recursive approach would look like this:
- Initial stack:
[A] - Pop
A, visit, and push unvisited neighbors[B, C]. - Pop
C, visit, and push neighbors[B, F, G]. - Continue this process until the stack is empty.
Advantages of Non-recursive DFS
- Space Efficiency: Reduces the risk of stack overflow prevalent in recursive DFS for deep graphs.
- Control: Offers explicit control over the stack, beneficial for iterative manipulation and debugging.
Comparison Table
| Aspect | Recursive DFS | Non-recursive DFS |
| Implementation | Simpler due to implicit stack | Slightly more complex due to manual stack usage |
| Space Complexity | Can be high due to call stack | Generally lower, depends on stack |
| Limitations | Stack overflow in deeply nested calls | Limited by available system memory for the stack |
| Performance | Both are usually (vertices plus edges) | Same as recursive DFS |
Additional Details
Use Cases for Non-recursive DFS
- Backtracking: Often used in puzzles like mazes.
- Topological Sorting: In directed acyclic graphs.
- Cycle Detection: In directed and undirected graphs.
- Path Finding: Finding paths between nodes.
Optimizations
- For large graphs, minimize memory usage by using data structures like bloom filters for visited checks.
- Leverage bit manipulation for state representation in dense graphs.
Conclusion
Non-recursive DFS is an efficient and versatile algorithm to traverse and explore graphs. Its iterative nature avoids issues associated with recursion while maintaining the depth exploration philosophy intrinsic to DFS. Whether you're engineering a complex graph-based system or exploring theoretic computer science, understanding both recursive and non-recursive DFS implementations is indispensable.
Related reading
- Non-recursive implementation of Flood Fill algorithm?
- Non-Recursive Merge Sort
- Non-recursive merge sort with two nested loops - how?
- Non-trivial algorithm conversion from imperative to functional
- Not able to connect mongo with replica set to mongo compass
- NotEnoughReplicasException The size of the current ISR Set(2) is insufficient to satisfy the min.isr requirement of 3
- Normalizing the edit distance
- nth_element implementations complexities

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.