Depth-First Search (DFS) explores as far as possible along each branch before backtracking. It traverses the graph using a ___ and is often used to find ____ and detect ____.
The correct term for the first blank is stack, which is a data structure that follows the Last-In-First-Out (LIFO) principle. The second blank is connected components, which are sets of nodes that are reachable from one another. Finally, the third blank is cycles, which are paths that start and end at the same node.
DFS can be implemented using a recursive or iterative approach. The recursive approach is simpler to implement but may encounter a stack overflow error for large graphs. The iterative approach uses an explicit stack data structure to avoid the stack overflow error.
Here's an example of implementing DFS using an iterative approach in Python:
1from collections import defaultdict
2
3class Graph:
4 def __init__(self):
5 self.graph = defaultdict(list)
6
7 def add_edge(self, u, v):
8 self.graph[u].append(v)
9
10 def dfs(self, start):
11 visited = set()
12 stack = [start]
13
14 while stack:
15 vertex = stack.pop()
16 if vertex not in visited:
17 print(vertex, end=' ')
18 visited.add(vertex)
19
20 for neighbor in self.graph[vertex]:
21 if neighbor not in visited:
22 stack.append(neighbor)
23
24# Create a graph
25graph = Graph()
26graph.add_edge(0, 1)
27graph.add_edge(0, 2)
28graph.add_edge(1, 2)
29graph.add_edge(2, 0)
30graph.add_edge(2, 3)
31graph.add_edge(3, 3)
32
33# Perform DFS
34graph.dfs(2)