AI EXP 7 Anu
AI EXP 7 Anu
Experiment - 7
Name: Anoop Khude Roll No: 5
AIM
Write a program to implement travelling salesman problem using hill climbing algorithm.
Theory/Procedure/Algorithm
The Traveling Salesman Problem (TSP) is a classic example where a salesman must
visit a set of cities exactly once and return to the starting point while minimizing the
total distance travelled.
The TSP stands as one of the best known problems when it comes to work
with NP-hard problems, which implies that no known algorithm exists to
solve it in polynomial time. The problem can be summarized as follows :
"Given a set of cities and the cost of travel (or distance) between each
possible pairs, the TSP, is to find the best possible way of visiting all the
cities and returning to the starting point that minimize the travel cost (or
travel distance)." The exact solution to this problem with n cities can only be
determined through evaluating (n-1)!/2 possibilities.
Hill Climbing is a local search algorithm that iteratively moves towards the direction of
increasing improvement, aiming to find a better solution in the search space. Starting
from a random initial solution, it generates neighboring solutions and selects the one
with the lowest distance. The process repeats until no better neighbors are found.
Steps for Implementing Hill Climbing
1. Initialize the current route and calculate its distance.
2. Iterate to find the best neighboring route until no improvement is found.
3. Return the best route and its distance .
Algorithm :
Distance Calculation: The calculate_distance function computes the total distance for a given tour
using the distance matrix.
Initial Solution Generation: The generate_initial_solution function creates a randomized initial
tour.
Hill Climbing Process:
Example: The last section demonstrates how to set up a distance matrix and call the hill climbing
function, printing the results.
Bharati Vidyapeeth (Deemed to be University)
Department of Engineering and Technology, Kharghar, Navi Mumbai
Code
import random
import math
while True:
neighbors = []
for i in range(num_cities):
for j in range(i + 1, num_cities):
# Create a neighbor by swapping two cities
neighbor = current_solution[:]
neighbor[i], neighbor[j] = neighbor[j], neighbor[i]
neighbors.append(neighbor)
# If the best neighbor is better than the current solution, move to the neighbor
if best_distance < current_distance:
current_solution = best_neighbor
current_distance = best_distance
else:
break # No better neighbors, exit the loop
# Example usage
if __name__ == "__main__":
# Distance matrix example (symmetric)
distance_matrix = [
[0, 10, 15, 20],
[10, 0, 35, 25],
[15, 35, 0, 30],
[20, 25, 30, 0]
]
OUTPUT:
Conclusion
Hence, this program effectively demonstrates the implementation of TSP using hill climbing
algorithm.
Bharati Vidyapeeth (Deemed to be University)
Department of Engineering and Technology, Kharghar, Navi Mumbai
Assessment