Ai Exp3

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

******************************************************************

EXPERIMENT NO. 3
Name :-
Class : T.E. COMPUTER SUB : A . I
Roll No :
Date of conductance : /0 /2024 Date of submission : / 0 /2024
******************************************************************

Aim :- Implementation of BFS algorithm.

Program :-

from collections import deque

def bfs(graph, start, goal):


# Using a deque to implement the queue for BFS
queue = deque([(start, [start])])

while queue:
current_node, path = queue.popleft()

if current_node == goal:
return path

for neighbour in graph[current_node]:


if neighbour not in path:
queue.append((neighbor, path + [neighbour]))

return None # If no path is found

# Example graph represented as an adjacency list


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

# Accepting initial and goal nodes from the user


initial_node = input("Enter the initial node: ")
goal_node = input("Enter the goal node: ")
# Performing BFS and printing the result
path_result = bfs(graph, initial_node, goal_node)

if path_result:
print(f"Path from {initial_node} to {goal_node}: {path_result}")
else:
print(f"No path found from {initial_node} to {goal_node}")

Program Output:-
Enter the initial node: A
Enter the goal node: F
Path from A to F: ['A', 'C', 'F']

You might also like