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

Bfs Dfs Time Space Ex11

The document contains a Python program that implements a Breadth-First Search (BFS) algorithm for traversing a graph. It defines a graph using a dictionary and performs BFS starting from node 'A', printing the nodes in the order they are visited. The output of the traversal is 'ABCDEFGH'.

Uploaded by

2005mathesh
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)
2 views1 page

Bfs Dfs Time Space Ex11

The document contains a Python program that implements a Breadth-First Search (BFS) algorithm for traversing a graph. It defines a graph using a dictionary and performs BFS starting from node 'A', printing the nodes in the order they are visited. The output of the traversal is 'ABCDEFGH'.

Uploaded by

2005mathesh
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/ 1

PROGRAM:

from collections import deque

# Function to perform Breadth-First Search

def bfs(graph, start):

queue = deque()

queue.append(start)

visited = set()

visited.add(start)

while queue:

current_node = queue.popleft()

print(current_node, end=' ')

for neighbor in graph[current_node]:

if neighbor not in visited:

queue.append(neighbor)

visited.add(neighbor)

if __name__ == "__main__":

graph = {

'A': ['B', 'C'],

'B': ['A', 'D', 'E'],

'C': ['A', 'F', 'G'],

'D': ['B'],

'E': ['B', 'H'],

'F': ['C'],

'G': ['C'],

'H': ['E']

print("BFS traversal starting from node 'A':")

bfs(graph, 'A')

OUTPUT:

BFS traversal starting from node 'A':

ABCDEFGH

You might also like