# Demo entry 6658802

show

Submitted by anonymous on Nov 08, 2017 at 12:40
Language: Python 3. Code size: 1.2 kB.

```import math

from aco import ACO, Graph
from plot import plot

#获取两个城市之间的距离
def distance(city1: dict, city2: dict):
return math.sqrt((city1['x'] - city2['x']) ** 2 +\
(city1['y'] - city2['y']) ** 2)

def main():
cities = [] #存储城市(字典形式)
points = [] #存储坐标(元组形式)
with open('./data/chn31.txt') as f: #从text文件中导入城市和坐标
for line in f.readlines():
city = line.split(' ')
cities.append(dict(index=int(city), \
x=int(city), y=int(city)))
points.append((int(city), int(city)))

cost_matrix = [] #存储城市i和j之间的距离 cost_matrix[i][j]
rank = len(cities)
for i in range(rank):
row = []
for j in range(rank):
row.append(distance(cities[i], cities[j]))
cost_matrix.append(row)

#创建ACO对象，并且设定好初始化参数
aco = ACO(10, 100, 1.0, 10.0, 0.5, 10, 2)
graph = Graph(cost_matrix, rank)
path, cost = aco.solve(graph) #返回最终path和cost
print('cost: {}, path: {}'.format(cost, path)) #打印运行结果
plot(points, path) #根据坐标和路径绘图

if __name__ == '__main__':
main()
```

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.