Week 4
Week 4
WEEK- 04
NAME:M.Sandeep Kumar DATE:02-04-2024
ROLL NO: 22R21A66A4 CLASS:CSM-B
AIM:Write a program to find shortest route that visits each city exactly once and returns to original
city using hill climbing algorithm
SOURCE CODE:
import random
def random_solution(tsp):
cities = list(range(len(tsp)))
solution = []
for i in range(len(tsp)):
random_city = cities[random.randint(0, len(cities) - 1)]
solution.append(random_city)
cities.remove(random_city)
return solution
def route_length(tsp, solution):
length = 0
for i in range(len(solution)):
length += tsp[solution[i - 1]][solution[i]]
return length
def get_neighbors(solution):
neighbors = []
for i in range(len(solution)):
for j in range(i + 1, len(solution)):
neighbor = solution.copy()
neighbor[i], neighbor[j] = neighbor[j], neighbor[i]
neighbors.append(neighbor)
return neighbors
def get_best_neighbor(tsp, neighbors):
best_length = route_length(tsp, neighbors[0])
best_neighbor = neighbors[0]
for neighbor in neighbors:
current_length = route_length(tsp, neighbor)
if current_length < best_length:
best_length = current_length
best_neighbor = neighbor
return best_neighbor, best_length
def hill_climbing(tsp):
current_solution = random_solution(tsp)
current_length = route_length(tsp, current_solution)
while True:
neighbors = get_neighbors(current_solution)
best_neighbor, best_length = get_best_neighbor(tsp, neighbors)
if best_length >= current_length:
break
current_solution, current_length = best_neighbor, best_length
return current_solution, current_length
tsp = [
[0, 400, 600, 200],
[400, 0, 300, 200],
[200, 300, 0, 400],
[300, 500, 200, 0]
]
print(hill_climbing(tsp))
OUTPUT: