The user wants a program to solve the Traveling Salesman Problem (TSP).
The TSP is a classic NP-hard problem. Given a set of cities and the distances between every pair of cities, the goal is to find the shortest possible route that visits every city exactly once and returns to the origin city.
I need to decide on the programming language and the specific algorithm(s) to implement.
Language: Python is a good choice because it's readable and widely used for algorithmic demonstrations. C++ is faster, but Python is more accessible for a general request.
Algorithms:
- Brute Force: Checking all permutations. O(N!). Only feasible for very small N (< 10). Good for verification.
- Dynamic Programming (Held-Karp): O(N22N). Good for N up to about 20-25.
- Nearest Neighbor (Greedy): Fast, but not optimal. O(N2).
- Genetic Algorithms / Simulated Annealing: Heuristics for larger N.
Given the request is just "write a program," I should provide a robust solution that isn't just brute force (too slow) but isn't overly complex to implement in a single script without external libraries like scipy or networkx (though using standard libraries like itertools is fine).
I will provide a Python solution.
I'll structure it to include:
-
A City class or structure.
-
A way to generate random cities.
-
A solver.
- Decision: Since TSP is hard, I should probably implement a standard exact solution (like Held-Karp or Branch and Bound) or a very common heuristic. However, for a general audience, showing the difference between a naive approach and a slightly better one is educational.
- Let's stick to Held-Karp (Dynamic Programming) as the "core" solver because it's the standard polynomial-space exact algorithm. It's efficient enough to demonstrate logic without timing out immediately on 15 cities.
- I'll also include a Simulated Annealing or 2-Opt heuristic because real-world TSP requires heuristics for N>20.
- Actually, let's keep it simpler. A complete TSP solver in one file usually implies either a DP solution for exactness or a heuristic for speed.
- Let's go with Simulated Annealing. It's elegant, handles larger datasets (e.g., 100 cities), and is conceptually interesting. Or, maybe 2-Opt with a random start.
- Alternative: Provide two methods. 1. Brute Force (for N < 10) to show the concept. 2. A simple heuristic like Nearest Neighbor or 2-Opt for larger N.
Let's refine the plan.
Most people asking for "a TSP solver" want to see an algorithm that actually works on a decent number of cities.
I will provide a Simulated Annealing solution. It's probabilistic, finds good solutions, and is standard for this problem without external libraries. It's also easier to implement concisely than Held-Karp (which requires bitmask logic that might confuse beginners).
Wait, Held-Karp is the "computer science" textbook answer. Simulated Annealing is the "engineering" answer. I will provide a Python script that uses Simulated Annealing because it can solve a visual TSP (e.g., 50-100 cities) in seconds, whereas DP would freeze.
Since the TSP is an NP-hard problem, finding the exact optimal solution for a large number of cities is computationally impossible within a reasonable time. This program implements two approaches:
- Exact Solver (Brute Force): Guaranteed to find the shortest path, but very slow. Only usable for N<10 cities.
- Heuristic Solver (2-Opt Local Search): Finds a near-perfect solution very quickly. This is the standard approach for real-world TSP problems.
Python Implementation
import math
import random
import time
import itertools
class City:
def __init__(self, x, y):
self.x = x
self.y = y
def distance_to(self, other):
return math.hypot(self.x - other.x, self.y - other.y)
def __repr__(self):
return f"({self.x},{self.y})"
class TSP_Solver:
def __init__(self, cities):
self.cities = cities
self.num_cities = len(cities)
def total_distance(self, route):
"""
Calculates the total distance of a specific route (list of City objects).
The route connects back to the start at the end.
"""
dist = 0
for i in range(len(route)):
from_city = route[i]
to_city = route[(i + 1) % len(route)]
dist += from_city.distance_to(to_city)
return dist
def solve_brute_force(self):
"""
Exact Solver: Tries every permutation.
Complexity: O(N!)
Warning: Extremely slow for N > 10.
"""
if self.num_cities > 10:
print("Warning: Brute force is too slow for > 10 cities.")
return None, float('inf')
print(f"Calculating Brute Force solution for {self.num_cities} cities...")
start_time = time.time()
min_distance = float('inf')
best_route = None
# We keep the first city fixed to reduce permutations by a factor of N
# because a cycle [A, B, C] is the same length as [B, C, A].
fixed_start = self.cities[0]
permutations = itertools.permutations(self.cities[1:])
for p in permutations:
current_route = [fixed_start] + list(p)
current_dist = self.total_distance(current_route)
if current_dist < min_distance:
min_distance = current_dist
best_route = current_route
end_time = time.time()
print(f"Brute Force finished in {end_time - start_time:.4f} seconds.")
return best_route, min_distance
def solve_two_opt(self, improvement_threshold=0.001):
"""
Heuristic Solver: 2-Opt Local Search.
1. Starts with a random route.
2. Iteratively improves the route by "uncrossing" lines (swapping segments).
3. Stops when no significant improvement is found.
"""
print(f"Calculating 2-Opt Heuristic solution for {self.num_cities} cities...")
start_time = time.time()
# 1. Initial solution (Random)
route = self.cities[:]
random.shuffle(route)
improvement_factor = 1.0
iterations = 0
while improvement_factor > improvement_threshold:
previous_distance = self.total_distance(route)
# 2. Try to swap every pair of edges
# We skip first and last because they connect to each other
for i in range(1, self.num_cities - 2):
for j in range(i + 1, self.num_cities):
# Current edges are (i-1, i) and (j, j+1)
# We check if swapping segment i...j improves distance
# Extract indices for easier math
# Note: In 2-opt, we reverse the segment between i and j
# Calculate current distance of two edges
d_curr = (route[i-1].distance_to(route[i]) +
route[j].distance_to(route[(j+1) % self.num_cities]))
# Calculate new distance if we swap
d_new = (route[i-1].distance_to(route[j]) +
route[i].distance_to(route[(j+1) % self.num_cities]))
if d_new < d_curr:
# Perform the swap (reverse the middle segment)
route[i:j+1] = reversed(route[i:j+1])
# 3. Check convergence
new_distance = self.total_distance(route)
improvement_factor = 1 - (new_distance / previous_distance)
iterations += 1
if iterations > 1000: break # Safety break
end_time = time.time()
print(f"2-Opt finished in {end_time - start_time:.4f} seconds ({iterations} improvement loops).")
return route, new_distance
# --- Helper to generate cities ---
def generate_random_cities(num_cities, x_range, y_range):
return [City(random.randint(*x_range), random.randint(*y_range)) for _ in range(num_cities)]
# --- Visualization (Optional) ---
def plot_route(route, title="TSP Route"):
try:
import matplotlib.pyplot as plt
except ImportError:
print("\nMatplotlib not found. Skipping visualization. (Install with: pip install matplotlib)")
return
x = [city.x for city in route] + [route[0].x]
y = [city.y for city in route] + [route[0].y]
plt.figure(figsize=(8, 6))
plt.plot(x, y, 'b-', zorder=1) # Line
plt.scatter(x[:-1], y[:-1], c='r', s=50, zorder=2) # Dots
plt.title(title)
plt.xlabel("X")
plt.ylabel("Y")
plt.grid(True)
plt.show()
# --- Main Execution ---
if __name__ == "__main__":
# 1. Small dataset to compare Exact vs Heuristic
print("="*50)
print("TEST 1: Small Set (N=6) - Comparing Accuracy")
print("="*50)
small_cities = generate_random_cities(6, (0, 100), (0, 100))
solver_small = TSP_Solver(small_cities)
bf_route, bf_dist = solver_small.solve_brute_force()
print(f"Brute Force Distance: {bf_dist:.2f}")
plot_route(bf_route, "Brute Force (Exact)")
h_route, h_dist = solver_small.solve_two_opt()
print(f"2-Opt Distance: {h_dist:.2f}")
plot_route(h_route, "2-Opt (Heuristic)")
# 2. Large dataset to show Heuristic speed
print("\n" + "="*50)
print("TEST 2: Large Set (N=50) - Performance Test")
print("="*50)
large_cities = generate_random_cities(50, (0, 500), (0, 500))
solver_large = TSP_Solver(large_cities)
# Brute force is skipped here; it would take years to finish N=50
route, dist = solver_large.solve_two_opt()
print(f"Final Path Distance: {dist:.2f}")
plot_route(route, "2-Opt Solution (50 Cities)")
How it Works
-
Brute Force (solve_brute_force):
- It generates every possible ordering of cities.
- It calculates the distance for every ordering.
- It picks the lowest number.
- Result: Mathematically perfect, but computationally explosive. For 50 cities, the number of permutations is 50!≈3×1064. This would take billions of years to run.
-
2-Opt Heuristic (solve_two_opt):
- Initialization: It starts with a random messy path.
- Optimization: It looks for "crossed lines" (like an 'X' shape) in the path. If uncrossing the lines (swapping the destinations) makes the total path shorter, it performs the swap.
- Convergence: It repeats this process until it can no longer find improvements.
- Result: Not mathematically guaranteed to be perfect, but usually finds a path that is very close to the optimal solution in a fraction of a second.
Requirements
To run this code, you only need standard Python.
- Standard Library:
math, random, time, itertools.
- Visualization (Optional): The code attempts to import
matplotlib to draw the map. If you don't have it, the code will still print the text results. You can install matplotlib via terminal:
pip install matplotlib