We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 3
DEPARTMENT OF
15 COMPUTER SCIENCE 8. ENGINEERING
Discover. Learn. Empower.
EXPERIMENT: 1.2
Student Name: Vishal Kumar Singh UID: 21BCS2439
Branch: CSE Section/Group: 702-B
Semester: 5" Date of Performance: 21/8/23
Subject Name: AIML Subject Code: 21CSH-316
Implement the BFS algorithm and analyse its performance and characteristics.
Objective: The objective of this experiment is to implement the Breadth-First Search
(BFS) algorithm and analyze its performance and characteristics.
Theory:
Breadth-first search is a graph traversal algorithm that starts traversing the graph from
the root node and explores all the neighboring nodes. Then, it selects the nearest node
and explores all the unexplored nodes. While using BFS for traversal, any node in the
graph can be considered as the root node.
Applications of BFS algorithm
The applications of breadth-first-algorithm are given as follows -
o BES can be used to find the neighbouring locations from a given source location.
o BFS is used to determine the shortest path and minimum spanning tree.
Complexity of BFS algorithm
Time complexity of BFS depends upon the data structure used to represent the graph.
The time complexity of BFS algorithm is O(V+E), since in the worst case, BFS
algorithm explores every node and edge. In a graph, the number of vertices is O(V),
whereas the number of edges is O(E).
The space complexity of BFS can be expressed as O(V), where V is the number of
vertices.DEPARTMENT OF
12) COMPUTER SCIENCE & ENGINEERING
Discover. Learn. Empower.
Program code:
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)
def bfs(self, start):
visited = set() queue
= deque({start])
visited.add(start)
while queue:
node = queue.popleft() print(node,
end="")
for neighbor in self.graph[node]:
if neighbor not in visited:
queue.append (neighbor) visited.add(neighbor)
= Graph()DEPARTMENT OF
15 COMPUTER SCIENCE & ENGINEERING
Siesta Di
iscover. Learn. Empower.
g.add_edge(1,
2)
g.add_edge(1,
3)
g.add_edge(2,
4)
g.add_edge(2,
5)
print("BFS Traversal starting from node 1:")
.bfs(1)
Outpu
Pan vey Mee NC we Meas es
Ce eae a eG ae Be
123456
PSEA ve Vwi creed
Learning Outcomes:
+ We leamt Breadth-first search technique along with its example.
We learnt Complexity, and implementation in python programming
language.
Evaluation Grid (To be created as per the SOP and Assessment guidelines by the
faculty):
Sr Parameters Marks Maximum
No. Obtained Marks
1