本关任务:编写一个爬山算法的小程序,通过局部搜索输出邻域范围内的最优解。
时间: 2023-10-29 09:05:45 浏览: 46
好的,下面是一个简单的 Python 实现,用于解决 TSP(Traveling Salesman Problem,旅行商问题):
```python
import random
import math
# 城市坐标
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 math.sqrt((city1[0]-city2[0])**2 + (city1[1]-city2[1])**2)
# 计算路径长度
def path_len(path):
length = 0
for i in range(len(path)-1):
length += distance(cities[path[i]], cities[path[i+1]])
return length
# 随机生成一个初始解
def init_solution(n):
return list(range(n))
# 对当前解进行邻域搜索
def neighborhood(solution):
neighborhoods = []
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]
neighborhoods.append(neighbor)
return neighborhoods
# 爬山算法
def hill_climbing():
# 初始化
current_solution = init_solution(len(cities))
current_length = path_len(current_solution)
print("Initial solution:", current_solution)
print("Initial length:", current_length)
# 迭代搜索
while True:
neighbors = neighborhood(current_solution)
neighbors_lengths = [(path_len(neighbor), neighbor) for neighbor in neighbors]
neighbors_lengths.sort()
if neighbors_lengths[0][0] >= current_length:
# 搜索结束,找到最优解
break
current_length, current_solution = neighbors_lengths[0]
print("Current solution:", current_solution)
print("Current length:", current_length)
# 输出最优解
print("Best solution found:", current_solution)
print("Best length found:", current_length)
if __name__ == '__main__':
hill_climbing()
```
这段代码会随机生成一个初始解,然后进行邻域搜索,每次选择路径长度更短的解作为当前解,直到找到最优解或达到最大迭代次数。最后输出最优解及其路径长度。