0% found this document useful (0 votes)
19 views

Submission of Lab 1 Implementation of Search Algorithms

Uploaded by

adelsiba7
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)
19 views

Submission of Lab 1 Implementation of Search Algorithms

Uploaded by

adelsiba7
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
You are on page 1/ 3

Submission of Lab 1: Implementation of Search Algorithms

import heapq
terrain_map = [
[1, 2, 2, 1, 4, 3, 2, 1],
[3, 2, 5, 1, 2, 4, 2, 1],
[2, 3, 5, 3, 3, 2, 4, 4],
[1, 3, 1, 1, 4, 1, 1, 2],
[3, 5, 1, 2, 4, 4, 1, 4],
[1, 3, 1, 1, 4, 5, 1, 1]
]

direction_vectors = [
(-1, 0), (-1, 1), (0, 1), (1, 1),
(1, 0), (1, -1), (0, -1), (-1, -1)
]

start = (0, 0, 0)
goal = (5, 7, 0)

def manhattan_distance(x1, y1, x2, y2):


return abs(x1 - x2) + abs(y1 - y2)

def a_star_search(start, goal, terrain_map):


rows = len(terrain_map)
cols = len(terrain_map[0])

frontier = []
heapq.heappush(frontier, (0, start))

cost_so_far = {start: 0}
came_from = {start: None}

Untitled 1
while frontier:
_, current = heapq.heappop(frontier)

if (current[0], current[1]) == (goal[0], goal[1]):


break

for direction in range(8):


dx, dy = direction_vectors[direction]
next_x = current[0] + dx
next_y = current[1] + dy

if 0 <= next_x < rows and 0 <= next_y < cols:

rotation_cost = 1 if (direction != current[2]) e


new_cost = cost_so_far[current] + terrain_map[ne
next_state = (next_x, next_y, direction)

if next_state not in cost_so_far or new_cost < c


cost_so_far[next_state] = new_cost
priority = new_cost + manhattan_distance(nex
heapq.heappush(frontier, (priority, next_sta
came_from[next_state] = current

path = []
state = next_state if (current[0], current[1]) == (goal[0],
while state is not None:
path.append(state)
state = came_from[state]

path.reverse()
return cost_so_far, path

cost, path = a_star_search(start, goal, terrain_map)

Untitled 2
if path:
print("Path found:")
for node in path:
print(f"Node: {node}, Cost: {cost[node]}")
else:
print("No path found.")

Untitled 3

You might also like