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

Ai Exp3

Uploaded by

premsp24hmca
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)
3 views2 pages

Ai Exp3

Uploaded by

premsp24hmca
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/ 2

Experiment No : 03

Implement any un-inform search algorithm

from collections import deque

# Define the BFS function


def bfs(graph, start, goal):
# A queue to hold the nodes to visit
queue = deque([start])

# A set to keep track of visited nodes


visited = set()

# Dictionary to store the path


parent = {start: None}

while queue:
# Get the next node in the queue
node = queue.popleft()

# Check if we reached the goal


if node == goal:
# Reconstruct the path
path = []
while node is not None:
path.append(node)
node = parent[node]
return path[::-1] # Return reversed path

# Mark the node as visited


visited.add(node)

# Add neighbors to the queue


for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
parent[neighbor] = node

return None # Return None if there's no path

# Example graph represented as an adjacency list


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

# Example usage of BFS to find a path from 'A' to 'F'


start_node = 'A'
goal_node = 'F'
path = bfs(graph, start_node, goal_node)

print("Path from {} to {}:".format(start_node, goal_node), path)

OUTPUT :

You might also like