



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Artificial Intelligence study notes
Typology: Study notes
1 / 7
This page cannot be seen from the preview
Don't miss anything!




Breadth First Traversal (BFS) for a Graph Code:
from collections import defaultdict
class Graph:
def init(self):
self.graph = defaultdict(list)
def addEdge(self,u,v): self.graph[u].append(v)
def BFS(self, s):
visited = [False] * (len(self.graph))
queue = []
queue.append(s) visited[s] = True while queue:
s = queue.pop(0) print (s, end = " ")
for i in self.graph[s]: if visited[i] == False: queue.append(i) visited[i] = True
g = Graph() g.addEdge(0, 1) g.addEdge(0, 2) g.addEdge(1, 2) g.addEdge(2, 0)
self.graph = defaultdict(list)
def addEdge(self, u, v): self.graph[u].append(v)
def DFSUtil(self, v, visited):
visited.add(v) print(v, end=' ')
for neighbour in self.graph[v]: if neighbour not in visited: self.DFSUtil(neighbour, visited)
def DFS(self, v):
visited = set()
self.DFSUtil(v, visited)
if name == "main":
g = Graph() g.addEdge(0, 1) g.addEdge(0, 2) g.addEdge(1, 2) g.addEdge(2, 0) g.addEdge(2, 3) g.addEdge(3, 3) print("Following is DFS from (starting from vertex 2)")
g.DFS(2) Result: Iterative Depth First Traversal (Iterative DFS) for a Graph Code:
for node in self.adj[s]: if (not visited[node]): stack.append(node)
g = Graph(5); # Total 5 vertices in graph g.addEdge(1, 0); g.addEdge(0, 2); g.addEdge(2, 1); g.addEdge(0, 3); g.addEdge(1, 4); print("Following is Depth First Traversal") g.DFS(0) Result: