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

Practical-7

7. Write a program to solve travelling salesman problem.


 Travelling Salesman Problem (TSP): Given a set of cities and distances between every
pair of cities, the problem is to find the shortest possible route that visits every city
exactly once and returns to the starting point.
 The Traveling Salesman Problem (TSP) is a classic optimization challenge in which a
salesman must find the shortest route to visit a set of cities exactly once and return to
the starting city.
 This problem is NP-hard, meaning it becomes computationally complex as the number
of cities increases.
 TSP has practical applications in logistics, routing, and circuit design, and various
algorithms, including heuristics and metaheuristics, are used to find approximate
solutions efficiently.
 Solving TSP efficiently is essential for optimizing transportation and resource
allocation in various industries.
 Implementation using python:
import itertools

def calculate_total_distance(path, distances):


total_distance = 0
for i in range(len(path) - 1):
total_distance += distances[path[i]][path[i + 1]]
return total_distance

def traveling_salesman_bruteforce(cities, distances):


min_distance = float('inf')
min_path = None

for path in itertools.permutations(range(len(cities))):


path_distance = calculate_total_distance(path, distances)
if path_distance < min_distance:
min_distance = path_distance
min_path = path

return min_path, min_distance

def main():
# Example data: cities and their distances (replace with your own data)
cities = ["A", "B", "C", "D"]
distances = [
[0, 10, 15, 20],
[10, 0, 35, 25],
[15, 35, 0, 30],
[20, 25, 30, 0]
]

min_path, min_distance = traveling_salesman_bruteforce(cities, distances)

print("\nOptimal Tour:")
for idx in min_path:
print(cities[idx], end=" -> ")
print(cities[min_path[0]]) # Return to the starting city to complete the cycle

print(f"Minimum Distance: {min_distance}")

if __name__ == "__main__":
main()

Output:

You might also like