Depth-First Search (DFS)
DFS is a traversal technique used for exploring graphs or trees. It explores as far along a branch as possible before backtracking. DFS can be implemented recursively (using the call stack) or iteratively using an explicit stack.
Python
# Recursive DFS for a graph using an adjacency list
def dfs_recursive(node, visited, graph):
visited.add(node)
print(node, end=" ")
for neighbor in graph.get(node, []):
if neighbor not in visited:
dfs_recursive(neighbor, visited, graph)
# Iterative DFS for a graph
def dfs_iterative(start, graph):
visited = set()
stack = [start]
while stack:
node = stack.pop()
if node not in visited:
visited.add(node)
print(node, end=" ")
# Adding neighbors in reverse order can help mimic recursive DFS
stack.extend(reversed(graph.get(node, [])))
# Sample graph
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}
print("Recursive DFS:")
dfs_recursive('A', set(), graph) # Possible output: A B D E F C
print("\nIterative DFS:")
dfs_iterative('A', graph) # Output order may vary
When to Use
Use DFS when you need to explore all possible paths, such as in maze traversal or solving puzzles.