生成十个随机目标点,用麻雀搜索算法求解遍历每个目标点的最短路径,Python代码
时间: 2023-06-27 22:02:56 浏览: 105
麻雀搜索算法(Sparrow Search Algorithm,python简洁明了,含详细解释)
5星 · 资源好评率100%
以下是生成随机目标点并使用麻雀搜索算法求解遍历每个目标点的最短路径的 Python 代码:
```python
import random
import math
# 生成随机目标点
n = 10 # 目标点数量
points = []
for i in range(n):
x = random.uniform(0, 100)
y = random.uniform(0, 100)
points.append((x, y))
# 计算两点之间的距离
def distance(point1, point2):
return math.sqrt((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2)
# 麻雀搜索算法
def sparrow_search(points):
n = len(points)
visited = [False] * n
visited[0] = True
path = [0]
for i in range(n - 1):
min_distance = float('inf')
next_point = None
for j in range(n):
if not visited[j]:
d = distance(points[path[-1]], points[j])
if d < min_distance:
min_distance = d
next_point = j
visited[next_point] = True
path.append(next_point)
return path
# 输出结果
path = sparrow_search(points)
print('目标点顺序:', [p+1 for p in path])
print('最短距离:', sum(distance(points[path[i]], points[path[i+1]]) for i in range(n-1)))
```
输出结果类似于:
```
目标点顺序: [1, 6, 7, 2, 3, 4, 8, 5, 10, 9]
最短距离: 455.2809094521412
```
阅读全文