The user wants a Python implementation of a graph using an adjacency list representation.
The implementation needs to include "various traversal methods".
Standard traversal methods for graphs are Breadth-First Search (BFS) and Depth-First Search (DFS).
I need to define a class for the Graph.
The Graph class should handle:
Storing the adjacency list (likely a dictionary where keys are nodes and values are lists of neighbors).
Adding edges (and potentially nodes).
Performing BFS.
Performing DFS (both recursive and iterative versions are good to show).
Maybe a method to print the graph for visualization.
Let's structure the code.
Class Graph:
__init__(self): Initialize an empty dictionary.
add_edge(self, u, v): Add a connection from u to v. If it's undirected, add v to u and u to v. Let's stick to undirected for simplicity, or add a flag for directed. Let's stick to undirected as the default unless specified, but actually, a directed graph is often easier to reason about for general algorithms, but undirected is more common for simple examples. Let's implement an undirected graph by default, but keep the code flexible. Actually, strictly speaking, standard adjacency lists usually imply u -> [v1, v2]. Let's do undirected.
bfs(self, start_node): Implementation using a queue.
dfs(self, start_node): Implementation using a stack (iterative).
dfs_recursive(self, start_node): Implementation using recursion.
Refining the implementation details:
Adjacency List: self.adj_list = defaultdict(list) is a good way to handle it.
BFS: Needs visited set, queue. Process current, add neighbors if not visited.
DFS: Needs visited set, stack. Push start. Pop current, process, push neighbors if not visited.
DFS Recursive: Needs visited set passed around or kept as instance variable (better to pass or use closure to keep stateless).
Edge Cases:
Start node not in graph?
Disconnected graph? (The traversals will only cover the connected component).
Code Structure:
python
from collections import defaultdict, deque
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def add_edge(self, u, v):
self.graph[u].append(v)
self.graph[v].append(u) # For undirected
# BFS method
def bfs(self, start_node):
visited = set()
queue = deque([start_node])
visited.add(start_node)
while queue:
vertex = queue.popleft()
print(vertex, end=" ")
for neighbor in self.graph[vertex]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
# DFS Iterative
def dfs_iterative(self, start_node):
visited = set()
stack = [start_node]
while stack:
vertex = stack.pop()
if vertex not in visited:
print(vertex, end=" ")
visited.add(vertex)
# Add neighbors to stack.
# Note: To maintain order similar to recursion (left-to-right), we might need to reverse the neighbors list before pushing.
# But strictly, order doesn't matter for correctness.
for neighbor in reversed(self.graph[vertex]):
if neighbor not in visited:
stack.append(neighbor)
# DFS Recursive
def dfs_recursive(self, start_node, visited=None):
if visited is None:
visited = set()
visited.add(start_node)
print(start_node, end=" ")
for neighbor in self.graph[start_node]:
if neighbor not in visited:
self.dfs_recursive(neighbor, visited)
This looks solid. I will provide the code with comments and a usage example. I will also ensure type hinting is included for better clarity.
Wait, one thought on the DFS Iterative: standard implementation pushes neighbors. If I want to ensure I don't push duplicates, I can check visited before pushing, but checking visited only when popping is also valid and sometimes simpler (though results in a larger stack).
Actually, checking visited before pushing is slightly more efficient for the queue/stack size, but checking when popping ensures the node is processed only once.
The standard approach for Iterative DFS usually looks like this:
Push start.
Loop while stack not empty:
Pop node.
If not visited: mark visited, process.
Push unvisited neighbors.
This ensures we don't process a node twice.
For BFS:
Enqueue start, mark visited.
Loop while queue not empty:
Dequeue, process.
For each neighbor: if not visited, mark visited, enqueue.
I'll write the code clearly. I should probably mention that this assumes an undirected graph, but the logic holds for directed too (just remove the self.graph[v].append(u) line).
I will present:
The Class structure.
add_edge.
bfs.
dfs (Recursive).
dfs_iterative (Stack-based).
A helper to print the list.
An example execution block.
Here is a complete, robust implementation of a Graph using an Adjacency List in Python.
This implementation includes methods for adding edges, printing the graph, and performing the three most common traversal/search strategies: Breadth-First Search (BFS), Depth-First Search (DFS) Iterative, and DFS Recursive.
python
Key Concepts Explained
Adjacency List (self.adj_list):
We use a Python dictionary where the key is the node (vertex) and the value is a list of connected nodes. This is memory-efficient for sparse graphs (graphs with few edges).
Breadth-First Search (BFS):
Data Structure: Queue (FIFO). We use collections.deque for O(1) pops from the left.
Logic: Visit a node, add all its unvisited neighbors to the back of the queue, then process the next person in line. This guarantees you find the shortest path in an unweighted graph.
Depth-First Search (DFS) Iterative:
Data Structure: Stack (LIFO).
Logic: Visit a node, add neighbors to the stack. Immediately process the most recently added neighbor (going "deep") before processing earlier neighbors.
DFS Recursive:
Logic: Uses the computer's internal "call stack" to function exactly like the iterative stack version. It is often cleaner to write but can hit recursion depth limits on extremely large graphs.
from collections import deque
class Graph:
def __init__(self):
"""
Initialize an empty dictionary to hold the adjacency list.
Key: Node
Value: List of adjacent nodes
"""
self.adj_list = {}
def add_edge(self, u, v):
"""
Adds an undirected edge between node u and node v.
If the nodes don't exist, they are added to the graph.
"""
# Add node u and connection to v
if u not in self.adj_list:
self.adj_list[u] = []
self.adj_list[u].append(v)
# Add node v and connection to u (because the graph is undirected)
if v not in self.adj_list:
self.adj_list[v] = []
self.adj_list[v].append(u)
def print_graph(self):
"""
Prints the adjacency list representation of the graph.
"""
for vertex in self.adj_list:
print(f"{vertex} -> {' '.join(map(str, self.adj_list[vertex]))}")
def bfs(self, start_node):
"""
Breadth-First Search (Iterative).
Uses a Queue to explore neighbors layer by layer.
"""
if start_node not in self.adj_list:
print(f"Node {start_node} not found in graph.")
return
visited = set()
queue = deque([start_node])
visited.add(start_node)
print(f"\nBFS starting from {start_node}:")
while queue:
current_node = queue.popleft()
print(current_node, end=" ")
for neighbor in self.adj_list[current_node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
print() # Newline for clean output
def dfs_iterative(self, start_node):
"""
Depth-First Search (Iterative).
Uses a Stack to explore as deep as possible before backtracking.
"""
if start_node not in self.adj_list:
print(f"Node {start_node} not found in graph.")
return
visited = set()
# using a list as a stack (append/pop)
stack = [start_node]
print(f"\nDFS (Iterative) starting from {start_node}:")
while stack:
current_node = stack.pop()
if current_node not in visited:
visited.add(current_node)
print(current_node, end=" ")
# Add neighbors to stack.
# Note: We reverse the neighbor list so that the first neighbor
# is popped first, mimicking the recursive order visually.
for neighbor in reversed(self.adj_list[current_node]):
if neighbor not in visited:
stack.append(neighbor)
print()
def dfs_recursive(self, start_node, visited=None):
"""
Depth-First Search (Recursive).
Uses the system call stack.
"""
if start_node not in self.adj_list:
print(f"Node {start_node} not found in graph.")
return
if visited is None:
print(f"\nDFS (Recursive) starting from {start_node}:")
visited = set()
visited.add(start_node)
print(start_node, end=" ")
for neighbor in self.adj_list[start_node]:
if neighbor not in visited:
self.dfs_recursive(neighbor, visited)
# Only print newline at the very end of the initial call
if len(visited) == len(self.get_all_nodes()):
print()
def get_all_nodes(self):
return list(self.adj_list.keys())
# --- Usage Example ---
if __name__ == "__main__":
g = Graph()
# Creating a graph that looks like this:
# 0
# / \
# 1---2
# / \ \
# 3 4---5
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 2)
g.add_edge(1, 3)
g.add_edge(1, 4)
g.add_edge(2, 5)
g.add_edge(4, 5)
print("Graph Adjacency List:")
g.print_graph()
# Run Traversals
g.bfs(0) # Expected: 0 1 2 3 4 5
g.dfs_iterative(0)# Expected: 0 1 3 4 5 2
g.dfs_recursive(0)# Expected: 0 1 3 4 5 2