To implement Depth First Search (DFS) for a graph, we provide two approaches: recursive and iterative. Both methods traverse the graph starting from a specified node, visiting nodes in depth-first order.
Approach
Recursive DFS:
Uses the call stack to manage nodes.
Marks the current node as visited and recursively visits all adjacent unvisited nodes.
Simple to implement but may cause stack overflow for large graphs.
Iterative DFS:
Uses an explicit stack to manage nodes.
Processes nodes by pushing unvisited adjacent nodes onto the stack.
Avoids recursion depth limits and is efficient for large graphs.
Both implementations:
Use a set to track visited nodes.
Return the traversal order as a list.
Solution Code
python
def dfs_recursive(graph, start):
visited = set()
traversal_order = []
def dfs(node):
visited.add(node)
traversal_order.append(node)
for neighbor in graph.get(node, []):
if neighbor not in visited:
dfs(neighbor)
dfs(start)
return traversal_order
def dfs_iterative(graph, start):
visited = set()
stack = [start]
traversal_order = []
while stack:
node = stack.pop()
if node not in visited:
visited.add(node)
traversal_order.append(node)
for neighbor in reversed(graph.get(node, [])):
if neighbor not in visited:
stack.append(neighbor)
return traversal_order
Explanation
Recursive DFS:
Initialize a set visited to track visited nodes and a list traversal_order to record the sequence.
Define a nested function dfs that:
Marks the current node as visited and adds it to traversal_order.
Recursively applies dfs to each unvisited neighbor.
Initiate the traversal by calling dfs(start).
Iterative DFS:
Use a stack initialized with the start node.
While the stack is not empty:
Pop a node. If unvisited, mark it as visited and record it.
Push its neighbors onto the stack in reverse order (to match recursive order).
Both methods produce the same traversal order. The iterative approach reverses neighbor order to match recursion's behavior. Adjust neighbor processing order if specific traversal patterns are needed.