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

556 Assignment 2 (Aiml)

Uploaded by

khandupatil121
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)
21 views5 pages

556 Assignment 2 (Aiml)

Uploaded by

khandupatil121
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

ASSIGNMENT 2 – A* ALGORITHM

NAME: TINA SHARAD PAWAR

[Link].: UCE2023556

DIV: B

BATCH: B4

TITLE- Solve a puzzle like the 8-puzzle by representing the puzzle state as a graph and using

A* / best first to find the sequence of moves leading to the solved state.

CODE:
import heapq

class Node:
def __init__(self, name, parent=None, g=0, h=0):
[Link] = name [Link] =
parent # parent node self.g = g # cost
to reach current node self.h = h #
heuristic estimate to goal self.f = g +
h # total cost (f = g + h)

def __lt__(self, other):


return self.f < other.f

def a_star(start, goal, graph, heuristic):


open_list = []
open_dict = {} # node_name -> best g cost found

start_node = Node(start, None, 0, heuristic[start])


[Link](open_list, start_node)
open_dict[start] = 0

while open_list:
current_node = [Link](open_list)

# Skip if this is not the best g cost for the node if


current_node.g > open_dict.get(current_node.name, float('inf')):
continue

# Goal check if
current_node.name == goal:
path = [] total_cost =
current_node.g
while current_node:
[Link](current_node.name)
current_node = current_node.parent return
path[::-1], total_cost

# Explore neighbors for neighbor, cost in


graph[current_node.name].items():
g_cost = current_node.g + cost
h_cost = heuristic[neighbor]

# If better path found to neighbor if


g_cost < open_dict.get(neighbor, float('inf')):
neighbor_node = Node(neighbor, current_node, g_cost, h_cost)
[Link](open_list, neighbor_node) open_dict[neighbor]
= g_cost

return None, None

def get_graph_input():
graph = {} n = int(input("\nEnter the
number of nodes: ")) print("Enter the graph
data:") for _ in range(n):
node = input("Enter node name: ").strip().upper()
neighbors = input(f"Enter neighbors for {node} (format:
neighbor1:cost, neighbor2:cost): ").strip()
neighbors_dict = {} if neighbors:
for neighbor in [Link](','):
parts = [Link](':')
if len(parts) == 2:
neighbor_name = parts[0].strip().upper()
try:
cost = int(parts[1].strip())
neighbors_dict[neighbor_name] = cost except
ValueError:
print(f"Invalid cost for neighbor '{parts[0]}'. Please
enter an integer.") else:
print(f"Invalid neighbor format: '{neighbor}'. Please
use format 'neighbor:cost'.") graph[node] = neighbors_dict return
graph

def get_heuristics_input(graph):
heuristic = {}
print("\nEnter heuristic values for each node (straight-line distance to
goal):") for node in graph: while True: try:
h_value = int(input(f"Enter heuristic value for {node}:
").strip())
heuristic[node] = h_value
break except ValueError:
print("Invalid input. Please enter an integer for the heuristic
value.")
return heuristic

def main():
graph = get_graph_input()
heuristic = get_heuristics_input(graph)

start = input("\nEnter the start node: ").strip().upper()


goal = input("Enter the goal node: ").strip().upper()

print("\nCalculating shortest path using A* algorithm...\n")


path, cost = a_star(start, goal, graph, heuristic)

if path:
print("Path found:", " -> ".join(path))
print("Total cost:", cost) else:
print("No path found.")

if __name__ == "__main__":
main()

OUTPUT:
Enter the number of nodes: 5
Enter the graph data:
Enter node name: S
Enter neighbors for S (format: neighbor1:cost, neighbor2:cost): A:1, B:4
Enter node name: A
Enter neighbors for A (format: neighbor1:cost, neighbor2:cost): B:2, C:5, D:12
Enter node name: B
Enter neighbors for B (format: neighbor1:cost, neighbor2:cost): C:2
Enter node name: C
Enter neighbors for C (format: neighbor1:cost, neighbor2:cost): D:3

Enter node name: D


Enter neighbors for D (format: neighbor1:cost, neighbor2:cost):

Enter heuristic values for each node (straight-line distance to goal):


Enter heuristic value for S: 7
Enter heuristic value for A: 6
Enter heuristic value for B: 2
Enter heuristic value for C: 1
Enter heuristic value for D: 0

Enter the start node: S


Enter the goal node: D

Calculating shortest path using A* algorithm...

Path found: S -> A -> B -> C -> D


Total cost: 8

You might also like