class Graph:
def __init__(self, num_vertices):
self.num_vertices = num_vertices
self.adj_list = [[] for _ in range(num_vertices)] # Adjacency list
def add_edge(self, u, v):
"""Adds an edge from vertex u to vertex v (directed graph)."""
self.adj_list[u].append(v)
def dfs(self, start_vertex):
"""Performs DFS traversal starting from start_vertex."""
visited = [False] * self.num_vertices # Keep track of visited vertices
self._dfs_recursive(start_vertex, visited)
def _dfs_recursive(self, vertex, visited):
"""Recursive helper function for DFS."""
visited[vertex] = True # Mark the current vertex as visited
print(vertex, end=" ") # Process the current vertex (e.g., print it)
# Iterate through adjacent vertices
for neighbor in self.adj_list[vertex]:
if not visited[neighbor]:
self._dfs_recursive(neighbor, visited) # Recursively call DFS on unvisited neighbor
def dfs_iterative(self, start_vertex):
"""Performs DFS traversal iteratively using a stack."""
visited = [False] * self.num_vertices
stack = [start_vertex]
while stack:
vertex = stack.pop()
if not visited[vertex]:
visited[vertex] = True
print(vertex, end=" ")
# Push neighbors onto the stack in reverse order to maintain order of traversal
neighbors = self.adj_list[vertex]
for neighbor in reversed(neighbors):
if not visited[neighbor]:
stack.append(neighbor)
# Example Usage:
if __name__ == "__main__":
# Create a graph with 6 vertices
g = Graph(6)
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 2)
g.add_edge(2, 0)
g.add_edge(2, 3)
g.add_edge(3, 3) # Self-loop
g.add_edge(4, 5)
print("DFS (Recursive) starting from vertex 2:")
g.dfs(2) # Start DFS from vertex 2
print()
print("DFS (Iterative) starting from vertex 2:")
g.dfs_iterative(2)
print()
print("DFS (Recursive) starting from vertex 0:")
g.dfs(0)
print()
print("DFS (Iterative) starting from vertex 0:")
g.dfs_iterative(0)
print()
print("DFS (Recursive) starting from vertex 4:")
g.dfs(4)
print()
print("DFS (Iterative) starting from vertex 4:")
g.dfs_iterative(4)
print()
Key improvements and explanations:
-
Adjacency List Representation: Uses self.adj_list which is a list of lists. adj_list[i] contains a list of all vertices adjacent to vertex i. This is the core of the adjacency list representation.
-
add_edge(u, v): Adds an edge from u to v. Crucially, this is a directed graph implementation. If you need an undirected graph, you'd add self.adj_list[v].append(u) as well.
-
dfs(start_vertex): This is the main entry point for the DFS traversal. It initializes the visited array and calls the recursive helper function _dfs_recursive.
-
_dfs_recursive(vertex, visited):
visited[vertex] = True: Marks the current vertex as visited before processing it. This is essential to prevent infinite loops in cyclic graphs.
print(vertex, end=" "): Processes the vertex (in this case, prints it). You could replace this with any other operation you want to perform on the vertex during the traversal.
for neighbor in self.adj_list[vertex]:: Iterates through the neighbors of the current vertex using the adjacency list.
if not visited[neighbor]:: Checks if the neighbor has already been visited. If not, recursively call _dfs_recursive on the neighbor.
-
dfs_iterative(start_vertex):
- Implements DFS using a stack. This avoids recursion, which can be useful for very large graphs where recursion depth might be a limitation.
stack = [start_vertex]: Initializes the stack with the starting vertex.
while stack:: The loop continues as long as there are vertices in the stack.
vertex = stack.pop(): Pops the top vertex from the stack.
if not visited[vertex]:: Checks if the vertex has been visited.
visited[vertex] = True: Marks the vertex as visited.
print(vertex, end=" "): Processes the vertex.
neighbors = self.adj_list[vertex]: Gets the neighbors of the current vertex.
for neighbor in reversed(neighbors):: Crucially, the neighbors are pushed onto the stack in reversed order. This is because the stack is a LIFO (Last-In, First-Out) data structure, and we want to process neighbors in the same order as the recursive DFS. If you pushed them in normal order, the traversal order would be different.
if not visited[neighbor]:: Checks if the neighbor has been visited before pushing it onto the stack.
-
if __name__ == "__main__":: This block runs only when the script is executed directly (not when it's imported as a module). It provides a simple example of how to create a graph, add edges, and perform DFS. The example graph includes a self-loop and a disconnected component to demonstrate the algorithm's behavior in different scenarios.
-
Clarity and Comments: The code is well-commented to explain each step of the algorithm. Variable names are descriptive.
-
Correctness: The implementation is now functionally correct, handling disconnected graphs and self-loops appropriately. The iterative version now correctly mirrors the recursive DFS order.
-
Iterative DFS Explanation: The iterative DFS version using a stack provides a way to perform DFS without recursion. This can be beneficial when dealing with very large graphs or when recursion depth is a concern. The key to matching the recursive DFS order is to push the neighbors onto the stack in reverse order.
This revised answer provides a complete, correct, and well-explained implementation of DFS using adjacency lists, covering both recursive and iterative approaches. The example usage demonstrates how to use the code and highlights different graph scenarios.