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

Week 4

The document describes a program that uses a hill climbing algorithm to find the shortest route that visits each city exactly once and returns to the original city. The program takes a travel salesman problem as input, generates random solutions, and iteratively chooses the neighbor with the shortest path length until no improvements can be found.

Uploaded by

ABINAY REDDY
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Week 4

The document describes a program that uses a hill climbing algorithm to find the shortest route that visits each city exactly once and returns to the original city. The program takes a travel salesman problem as input, generates random solutions, and iteratively chooses the neighbor with the shortest path length until no improvements can be found.

Uploaded by

ABINAY REDDY
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

ARTIFICIAL INTELLIGENCE LAB

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:

([0, 1, 3, 2], 1200)

You might also like