bai2
bai2
bai2
import itertools
class Graph:
def __init__(self, adjac_lis):
self.adjac_lis = adjac_lis
self.cities = list(adjac_lis.keys()) # List of cities
# Holds the current distances from the start city to all other cities
poo = {}
poo[(start, tuple([start]))] = 0
while open_lst:
# Find the node with the lowest f() = g() + h()
n = min(open_lst, key=lambda x: poo[x] + self.h(x[1], x[0]))
current_city, visited_cities = n
# Explore neighbors
unvisited_cities = [city for city in self.cities if city not in
visited_cities]
for city in unvisited_cities:
new_visited_cities = tuple(sorted(visited_cities + (city,)))
new_cost = poo[n] + next(
cost for neighbor, cost in self.get_neighbors(current_city) if
neighbor == city
)
# Define the graph with adjacency list. Each node has a list of its neighbors and
the edge weights.
adjac_lis = {
'1': [('2', 10), ('3', 15), ('4', 20)],
'2': [('1', 10), ('3', 35), ('4', 25)],
'3': [('1', 15), ('2', 35), ('4', 30)],
'4': [('1', 20), ('2', 25), ('3', 30)],
}
# Example: Find the shortest path visiting all cities starting from '1'
graph.a_star_algorithm('1')