Varun Aiml Rec3

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

VARUN SRINIVAS

ARAVIND S A

311522205005
311522205056

PROGRAM:

from queue import PriorityQueue


def heuristic(a, b):
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def construct_path(came_from, start, goal):
path = []
node = goal
while node != start:
path.append(node)
node = came_from[node]
path.append(start)
path.reverse()
return path
def shortest_path(graph, start, goal):
frontier = PriorityQueue()
frontier.put((0, start))
came_from = {}
cost_so_far = {}
came_from[start] = None
cost_so_far[start] = 0
while not frontier.empty():
current_cost, current_node = frontier.get()
if current_node == goal:
break
for next_node in graph[current_node]:
new_cost = cost_so_far[current_node] + graph[current_node][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
priority = new_cost + heuristic(goal, next_node)
frontier.put((priority, next_node))
came_from[next_node] = current_node
return came_from, cost_so_far
graph = {
(0, 0): {(0, 1): 1, (1, 0): 1},
(0, 1): {(0, 0): 1, (1, 1): 1, (0, 2): 1},
(1, 0): {(0, 0): 1, (1, 1): 1},
(1, 1): {(0, 1): 1, (2, 2): 1}
}
start = (0, 0)
goal = (1, 1)
came_from, cost_so_far = shortest_path(graph, start, goal)
path = construct_path(came_from, start, goal)
print('shortest path:', path)

OUTPUT:

You might also like