X

We would like to inform you that the domain chat-to.dev, as well as the associated project, is available for purchase. Those interested in negotiating or obtaining more information can contact us at contact@chat-to.dev.

We would like to thank everyone who has followed and supported the project so far.

1715347541

User Implementation challenges for graph search algorithms in python


Let's consider an example of implementing Depth-First Search (DFS) and Breadth-First Search (BFS) algorithms in Python to traverse a graph represented using an adjacency list. ```py from collections import defaultdict class Graph: def __init__(self): self.graph = defaultdict(list) def add_edge(self, u, v): self.graph[u].append(v) def dfs_util(self, v, visited): visited.add(v) print(v, end=' ') for neighbor in self.graph[v]: if neighbor not in visited: self.dfs_util(neighbor, visited) def dfs(self, start): visited = set() self.dfs_util(start, visited) def bfs(self, start): visited = set() queue = [start] visited.add(start) while queue: v = queue.pop(0) print(v, end=' ') for neighbor in self.graph[v]: if neighbor not in visited: queue.append(neighbor) visited.add(neighbor) # Example usage g = Graph() 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) print("DFS traversal:") g.dfs(2) print("\nBFS traversal:") g.bfs(2) ``` This code defines a simple graph class using an adjacency list representation. It includes methods to add edges, perform Depth-First Search (DFS), and Breadth-First Search (BFS) traversals. The **dfs_util** method is a recursive helper function for DFS traversal, while the **dfs** method initializes the visited set and starts DFS from a given node. Similarly, the **bfs** method performs BFS traversal using a queue. You can create a **Graph** object, add edges using the **add_edge** method, and then perform DFS or BFS traversal starting from any node using the respective methods.

(0) Comments

Welcome to Chat-to.dev, a space for both novice and experienced programmers to chat about programming and share code in their posts.

About | Privacy | Donate
[2026 © Chat-to.dev]