0% found this document useful (0 votes)
18 views6 pages

BFS Example

This Python code implements breadth-first search (BFS) on a graph data structure represented using an adjacency list. It defines a Graph class with methods to add edges and perform BFS starting from a given source vertex. BFS uses a queue to iteratively explore the neighbors of visited vertices until all reachable nodes are discovered. The code provides an example graph and prints the BFS traversal starting from vertex 2.

Uploaded by

Amara Manikanta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views6 pages

BFS Example

This Python code implements breadth-first search (BFS) on a graph data structure represented using an adjacency list. It defines a Graph class with methods to add edges and perform BFS starting from a given source vertex. BFS uses a queue to iteratively explore the neighbors of visited vertices until all reachable nodes are discovered. The code provides an example graph and prints the BFS traversal starting from vertex 2.

Uploaded by

Amara Manikanta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

CODE IN PYTHON

# Python3 Program to print BFS traversal

# from a given source vertex. BFS(int s)

# traverses vertices reachable from s.

from collections import defaultdict

# This class represents a directed graph

# using adjacency list representation

class Graph:

# Constructor

def __init__(self):

# Default dictionary to store graph

self.graph = defaultdict(list)

# Function to add an edge to graph

def addEdge(self, u, v):

self.graph[u].append(v)
# Function to print a BFS of graph

def BFS(self, s):

# Mark all the vertices as not visited

visited = [False] * (max(self.graph) + 1)

# Create a queue for BFS

queue = []

# Mark the source node as

# visited and enqueue it

queue.append(s)

visited[s] = True

while queue:

# Dequeue a vertex from

# queue and print it

s = queue.pop(0)

print(s, end=" ")

# Get all adjacent vertices of the

# dequeued vertex s.

# If an adjacent has not been visited,

# then mark it visited and enqueue it

for i in self.graph[s]:

if visited[i] == False:

queue.append(i)

visited[i] = True

# Driver code

if __name__ == '__main__':

# Create a graph given in

# the above diagram

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
Following is Breadth First Traversal (starting from vertex 2)
2 0 3 1

You might also like