0% found this document useful (0 votes)
6 views1 page

Exp. No 2 BFS

The document presents a Python implementation of a graph using a class structure. It includes methods for adding edges and performing a Breadth-First Search (BFS) traversal. The driver code allows user input to create the graph and initiate the BFS from a specified starting vertex.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views1 page

Exp. No 2 BFS

The document presents a Python implementation of a graph using a class structure. It includes methods for adding edges and performing a Breadth-First Search (BFS) traversal. The driver code allows user input to create the graph and initiate the BFS from a specified starting vertex.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

from collections import defaultdict

class Graph:
def __init__(self):
self.graph = defaultdict(list)
self.visited = []

def addEdge(self, u, v):


self.graph[u].append(v)

def BFS(self, start):


queue = []
queue.append(start)
self.visited.append(start)

while queue:
current_vertex = queue.pop(0)
print(current_vertex, end=" ")

for neighbor in self.graph[current_vertex]:


if neighbor not in self.visited:
queue.append(neighbor)
self.visited.append(neighbor)

# Driver code
g = Graph()

# Take user input for adding edges to the graph


while True:
try:
u = int(input("Enter the source vertex (or any non-integer to stop): "))
v = int(input("Enter the destination vertex: "))
g.addEdge(u, v)
except ValueError:
break

start_vertex = int(input("Enter the starting vertex for BFS: "))

print("Following is Breadth First Traversal (starting from vertex


{})".format(start_vertex))
g.BFS(start_vertex)

You might also like