You are on page 1of 3

Experiment 1.

Student Name: Abhishek UID: 21BCS3967


Branch: CSE Section/Group: 644-B (IOT)
Semester: 5TH Date of Performance: 23/8/23
Subject Name: AIML LAB Subject Code: 21CSH-316

Aim: Implement the BFS algorithm and analyze its performance and characteristics

Procedure/Algorithm/Code:
1. Create a queue data structure to store the vertices to be visited.
2. Mark the source vertex as visited and enqueue it.
3. While the queue is not empty, do the following:
a. Dequeue a vertex from the queue.
b. Process the dequeued vertex (e.g.,print it or perform any required operations).
c. Enqueue all the adjacent vertices of the dequeued vertex that are not visited and mark
them as visited.
4. Repeat steps 3 until the queue becomes empty.

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] * (max(self.graph) + 1)
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
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 Breadth First Traversal"


" (starting from vertex 2)")
g.BFS(2)

OUTPUT

You might also like