Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

Code;

import heapq

# Define the grid layout with obstacles (#)


grid = [
['S', '.', '.', '.', '#'],
['#', '#', '.', '#', '#'],
['.', '.', '.', '.', '.'],
['#', '.', '#', '.', '#'],
['.', '.', '.', '.', 'E']
]

# Define the possible movements (up, down, left, right)


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

# Define the heuristic function (Manhattan distance)


def heuristic(node, goal):
return abs(node[0] - goal[0]) + abs(node[1] - goal[1])

# Implement the A* search algorithm


def a_star_search(grid, start, end):
open_list = []
closed_set = set()
heapq.heappush(open_list, (0, start))
came_from = {}
cost_so_far = {start: 0}

while open_list:
current_cost, current_node = heapq.heappop(open_list)

if current_node == end:
break

closed_set.add(current_node)

for move in moves:


new_node = (current_node[0] + move[0], current_node[1] + move[1])

if (
0 <= new_node[0] < len(grid)
and 0 <= new_node[1] < len(grid[0])
and grid[new_node[0]][new_node[1]] != '#'
and new_node not in closed_set
):
new_cost = cost_so_far[current_node] + 1
if new_node not in cost_so_far or new_cost < cost_so_far[new_node]:
cost_so_far[new_node] = new_cost
priority = new_cost + heuristic(new_node, end)
heapq.heappush(open_list, (priority, new_node))
came_from[new_node] = current_node

# Reconstruct the path from the end point to the start point
path = []
current = end
while current != start:
path.append(current)
current = came_from[current]
path.append(start)
path.reverse()

return path, closed_set

1. # Print the original layout of the area


print("Original Layout:")
for row in grid:
print(" ".join(row))
print()

2. # Find the path using A* search algorithm


start = None
end = None
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 'S':
start = (i, j)
elif grid[i][j] == 'E':
end = (i, j)
if start is not None and end is not None:
path, closed_set = a_star_search(grid, start, end)

3. # Print the path length and searched squares count


print(f"Path Length: {len(path)}")
print(f"Searched Squares: {len(closed_set)}")
print()

4. # Print the path in the layout with '*'


print("Path:")
for i in range(len(grid)):
for j in range(len(grid[0])):
if (i, j) == start:
print('S', end=' ')
elif (i, j) == end:
print('E', end=' ')
elif (i, j) in path:
print('*', end=' ')
else:
print(grid[i][j], end=' ')
print()

Result:

Path Length : 9
Searched squares: 10

You might also like