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

AI Exp-3

Uploaded by

routkaran33
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)
7 views2 pages

AI Exp-3

Uploaded by

routkaran33
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

Program:
from collections import deque

def bfs(graph, start, goal):


# Initialize a queue with the start node
queue = deque([[start]])

# Keep track of the visited nodes


visited = set()

while queue:
# Get the first path from the queue
path = queue.popleft()

# Get the last node from the path


node = path[-1]

# If the node has been visited, skip it


if node in visited:
continue

# If the node is the goal, return the path


if node == goal:
return path

# Mark the node as visited


visited.add(node)

# Add paths with the neighbors of the current node to the queue
for neighbor in graph.get(node, []):
new_path = list(path)
new_path.append(neighbor)
queue.append(new_path)

# If no path is found, return None


return None

# Example graph represented as an adjacency list


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

# Example usage: find the path from 'A' to 'H'


path = bfs(graph, 'A', 'H')
print("Path from 'A' to 'H':", path)

OUTPUT:
Path from 'A' to 'H': ['A', 'B', 'E', 'H']

You might also like