0% found this document useful (0 votes)
12 views5 pages

Ai Ass 2

The document presents implementations of three search algorithms: Breadth-First Search (BFS), Depth-First Search (DFS), and Uniform-Cost Search (UCS) for navigating a weighted graph. It includes a user interface for selecting start and goal nodes, as well as the desired algorithm, and outputs the complete path, total nodes on the frontier, total nodes generated, and total path cost. An example execution shows the results of using UCS to find a path from node S to G.

Uploaded by

playstore9.ha
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)
12 views5 pages

Ai Ass 2

The document presents implementations of three search algorithms: Breadth-First Search (BFS), Depth-First Search (DFS), and Uniform-Cost Search (UCS) for navigating a weighted graph. It includes a user interface for selecting start and goal nodes, as well as the desired algorithm, and outputs the complete path, total nodes on the frontier, total nodes generated, and total path cost. An example execution shows the results of using UCS to find a path from node S to G.

Uploaded by

playstore9.ha
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/ 5

HAIDER ALI_B23F0001AI054_AI_Blue

from collections import deque


import heapq

# Define the weighted graph as an adjacency list with weights


graph = {
'S': {'A': 4, 'B': 5},
'A': {'S': 4, 'B': 3, 'G': 6},
'B': {'S': 5, 'A': 3, 'G': 2},
'G': {'A': 6, 'B': 2}
}

# Breadth-First Search def bfs(start, goal):


frontier = deque([start]) # Queue for BFS
visited = set() parent = {start: None}
nodes_generated = 1 # Start node is generated
while frontier:
current = frontier.popleft()
if current == goal:
break if current not in
visited:
visited.add(current)
# Sort neighbors alphabetically for tie-breaking
neighbors = sorted(graph[current].keys()) for
next_node in neighbors: if next_node not in
visited and next_node not in frontier:
frontier.append(next_node) parent[next_node]
= current nodes_generated += 1

# Reconstruct path path = []


current = goal while current is
not None:
path.append(current) current
= parent.get(current)
path.reverse()

return path, len(frontier) + len(visited), nodes_generated,


len(path) - 1

# Depth-First Search def dfs(start,


goal): frontier = [start] # Stack
for DFS
visited = set()
parent = {start: None}
nodes_generated = 1
while frontier:
current = frontier.pop()
if current == goal:
break if current not in
visited:
visited.add(current)
# Sort neighbors alphabetically and reverse for stack
(LIFO)
neighbors = sorted(graph[current].keys(), reverse=True)
for next_node in neighbors: if next_node not in
visited and next_node not in set(frontier):
frontier.append(next_node) parent[next_node] =
current nodes_generated += 1

# Reconstruct path path = []


current = goal while current is
not None:
path.append(current) current
= parent.get(current)
path.reverse()

return path, len(frontier) + len(visited), nodes_generated,


len(path) - 1

# Uniform-Cost Search def ucs(start, goal): frontier = [(0,


start)] # Priority queue with (cost, node) visited = set()
parent = {start: None} cost_so_far = {start: 0}
nodes_generated = 1
while frontier: current_cost, current =
heapq.heappop(frontier) if current == goal:
break if current not in visited:
visited.add(current)
neighbors = sorted(graph[current].keys()) # Alphabetical
tie-breaking for next_node in neighbors:
new_cost = current_cost + graph[current][next_node]
if next_node not in cost_so_far or new_cost <
cost_so_far[next_node]:
cost_so_far[next_node] = new_cost
heapq.heappush(frontier, (new_cost, next_node))
parent[next_node] = current if next_node not in
visited:
nodes_generated += 1

# Reconstruct path path = []


current = goal while current is
not None:
path.append(current) current
= parent.get(current)
path.reverse()

return path, len(frontier) + len(visited), nodes_generated,


cost_so_far.get(goal, 0)

# Input and execution logic directly in global scope


print("Available nodes:", list(graph.keys()))
start = input("Enter start state (e.g., S): ").strip().upper()
goal = input("Enter goal state (e.g., G): ").strip().upper() algo
= input("Choose algorithm (BFS, DFS, UCS): ").strip().upper()

if start not in graph or goal not in graph: print("Invalid start


or goal state!") else: if algo == "BFS": path,
frontier_size, nodes_generated, path_cost = bfs(start, goal)
elif algo == "DFS": path, frontier_size, nodes_generated,
path_cost = dfs(start, goal) elif algo == "UCS": path,
frontier_size, nodes_generated, path_cost = ucs(start, goal)
else: print("Invalid algorithm!")
path = [] # Set path to empty to avoid undefined variable
error
if path: # Only print results if a valid algorithm was chosen
print("\nResults:")
print("a. Complete path:", " -> ".join(path) if path[0] ==
start else "No path found")
print("b. Total nodes on frontier:", frontier_size)
print("c. Total nodes generated:", nodes_generated)
print("d. Total path cost:", path_cost)
Available nodes: ['S', 'A', 'B', 'G']

Enter start state (e.g., S): S


Enter goal state (e.g., G): G
Choose algorithm (BFS, DFS, UCS): UCS

Results:
a. Complete path: S -> B -> G
b. Total nodes on frontier: 4
c. Total nodes generated: 5
d. Total path cost: 7

You might also like