0% found this document useful (0 votes)
7 views2 pages

BFS Programs

Jld jj ulcujcmhkyfoyyjtbxngslisi5do6bngzixitd7i6zkyhxzykxpxu5ziyz.cnsi5zouzjyluxkuzmhJaky,tkjyzlyzyis5

Uploaded by

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

BFS Programs

Jld jj ulcujcmhkyfoyyjtbxngslisi5do6bngzixitd7i6zkyhxzykxpxu5ziyz.cnsi5zouzjyluxkuzmhJaky,tkjyzlyzyis5

Uploaded by

vardhanshannu73
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

## Program 1 ##

from collections import deque

def bfs(graph, start_node):


visited = set() # Set to keep track of visited nodes
queue = deque([start_node]) # Use deque for efficient FIFO queue
operations

print("BFS traversal:")

while queue:
node = [Link]()
if node not in visited:
print(node, end=" ")
[Link](node)
[Link](neighbor for neighbor in graph[node] if neighbor not
in visited)

# Example graph (adjacency list representation)


graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}

# Run BFS
bfs(graph, 'A')

## Program 2 ##

from collections import deque

def bfs(graph, start_node):


visited = set()
queue = deque([start_node])

print("BFS Traversal:")

while queue:
node = [Link]()
if node not in visited:
print(node, end=" ")
[Link](node)
[Link](neighbor for neighbor in graph[node] if neighbor not
in visited)

# Given graph
graph = {
'5': ['3', '7'],
'3': ['2', '4'],
'7': ['8'],
'2': [],
'4': ['8'],
'8': []
}

# Start BFS from node '5'


bfs(graph, '5')

## Program 3 ##

from collections import deque

# Graph as an adjacency list


graph = {
1: [2, 4, 5],
2: [1, 3, 6, 7],
3: [2],
4: [1],
5: [1],
6: [2],
7: [2]
}

def bfs(graph, start_node):


visited = set()
queue = deque([start_node])

print("BFS Traversal:", end=" ")


while queue:
node = [Link]()
if node not in visited:
print(node, end=" ")
[Link](node)
for neighbor in graph[node]:
if neighbor not in visited:
[Link](neighbor)

# Run BFS starting from node 1


bfs(graph, 1)

You might also like