python 解决 tsp旅行商问题
时间: 2023-10-22 10:09:15 浏览: 112
TSP问题是指旅行商问题,即在给定的一些城市之间寻找一条最短的路径,使得每个城市恰好被访问一次,最终回到起点城市。Python可以使用多种算法来解决TSP问题,其中比较常用的是遗传算法和模拟退火算法。
遗传算法的基本思想是通过模拟生物进化过程来搜索最优解。具体实现中,可以将每个城市看作一个基因,将所有城市的排列看作一个染色体,然后通过交叉、变异等操作来不断优化染色体,最终得到最优解。
模拟退火算法则是通过模拟物质在高温下的运动来搜索最优解。具体实现中,可以将每个城市看作一个状态,然后通过随机游走的方式来不断优化状态,最终得到最优解。
以下是一个使用遗传算法解决TSP问题的示例代码:
```python
import random
# 城市坐标
cities = [(60, 200), (180, 200), (80, 180), (140, 180), (20, 160),
(100, 160), (200, 160), (140, 140), (40, 120), (100, 120),
(180, 100), (60, 80), (120, 80), (180, 60), (20, 40),
(100, 40), (200, 40), (20, 20), (60, 20), (160, 20)]
# 计算两个城市之间的距离
def distance(city1, city2):
return ((city1[0] - city2[0]) ** 2 + (city1[1] - city2[1]) ** 2) ** 0.5
# 计算染色体的适应度
def fitness(chromosome):
total_distance = 0
for i in range(len(chromosome) - 1):
total_distance += distance(cities[chromosome[i]], cities[chromosome[i+1]])
total_distance += distance(cities[chromosome[-1]], cities[chromosome[0]])
return 1 / total_distance
# 初始化种群
def init_population(population_size, chromosome_length):
population = []
for i in range(population_size):
chromosome = list(range(chromosome_length))
random.shuffle(chromosome)
population.append(chromosome)
return population
# 选择操作
def selection(population, fitness_values):
total_fitness = sum(fitness_values)
probabilities = [fitness_value / total_fitness for fitness_value in fitness_values]
selected_indices = random.choices(range(len(population)), weights=probabilities, k=2)
return population[selected_indices[0]], population[selected_indices[1]]
# 交叉操作
def crossover(parent1, parent2):
child = [-1] * len(parent1)
start_index = random.randint(0, len(parent1) - 1)
end_index = random.randint(start_index, len(parent1) - 1)
for i in range(start_index, end_index + 1):
child[i] = parent1[i]
j = 0
for i in range(len(parent2)):
if parent2[i] not in child:
while child[j] != -1:
j += 1
child[j] = parent2[i]
return child
# 变异操作
def mutation(chromosome, mutation_rate):
for i in range(len(chromosome)):
if random.random() < mutation_rate:
j = random.randint(0, len(chromosome) - 1)
chromosome[i], chromosome[j] = chromosome[j], chromosome[i]
return chromosome
# 遗传算法主函数
def genetic_algorithm(population_size, chromosome_length, max_generations):
population = init_population(population_size, chromosome_length)
for generation in range(max_generations):
fitness_values = [fitness(chromosome) for chromosome in population]
best_chromosome = population[fitness_values.index(max(fitness_values))]
print('Generation {}: Best fitness = {}'.format(generation, max(fitness_values)))
new_population = [best_chromosome]
while len(new_population) < population_size:
parent1, parent2 = selection(population, fitness_values)
child = crossover(parent1, parent2)
child = mutation(child, 0.01)
new_population.append(child)
population = new_population
return best_chromosome
# 测试
best_chromosome = genetic_algorithm(100, len(cities), 1000)
print('Best chromosome:', best_chromosome)
```
阅读全文