1 简单介绍
2 随机算法
3 算法 描述
5 代码
- 本代码默认城市数为5
- 为了城市数作为下表,默认边边距离从1开始
- 可以从城市数自定义、边与边距离自定义、记录多条最优路径等改进代码
- 随机生成路径的方式还有很多,可以改进。
也许你会想怎么处理的两点无边的情况:
- so easy,只需要将两点无边的情况,让他有一个超级大的边,这样看似右边,实则无边。
- 因为要计算的是路径最小化,这么大的边即使被计算过,一定会被pass。
#include <iostream>
#include<algorithm>
using namespace std;
int city[5] = {1, 2, 3, 4, 5};
int cityNum = 5;
int path[5]={1, 2, 3, 4, 5};
int edge[6][6] =
{-1,-1,-1,-1,-1,-1,
-1, 0, 1, 3, 4, 5,
-1, 1, 0, 1, 2, 3,
-1, 3, 1, 0, 1, 2,
-1, 4, 2, 1, 0, 1,
-1, 5, 3, 2, 1, 0};
int edge1[6][6] =
{-1,-1,-1,-1,-1,-1,
-1, 0, 1,10,10, 5,
-1, 1, 0, 2, 1, 1,
-1,10, 2, 0, 3,10,
-1,10, 1, 3, 0, 4,
-1, 5, 1,10, 4, 0};
int distance(){
int sumdist = 0;
for(int i=0;i<cityNum-1;i++){
sumdist+= edge[path[i]][path[i+1]];
}
sumdist+= edge[path[cityNum-1]][path[0]];
return sumdist;
}
void randomPath(){
for(int i = 0; i < cityNum; i++){
int j = rand()%cityNum;
swap(path[i],path[j]);
}
}
void copy(int bestpath[]){
for(int i=0;i<cityNum;i++){
bestpath[i]=path[i];
}
}
void display(){
cout<<"the random path is:";
for(int i=0;i<cityNum;i++)
cout<<path[i]<<" ";
cout<<endl;
}
int main(int argc, char *argv[]){
cout<<"原始边矩阵:"<<endl;
for(int i=0;i<5;i++){
printf("%d %d %d %d %d\n",edge[i][0],edge[i][1],edge[i][2],edge[i][3],edge[i][4]);
}
int iteration = 1000;
int bestPath[cityNum];
int minDist=1000;
for(int i=0;i<iteration;i++){
randomPath();
display();
int curDist=distance();
cout<<"该随机路径的长度: "<<curDist<<endl;
if(curDist<minDist){
minDist=curDist;
copy(bestPath);
}
}
cout<<"the minDist is "<<minDist<<" the best path is:";
for(int i=0;i<cityNum;i++)
cout<<bestPath[i]<<" ";
cout<<endl;
return 0;
}