最近,人工智能课的作业,详细文档就不写了,感兴趣可以联系我,旨在交流。
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <time.h>
- #include <math.h>
- #define A 2
- #define B 3
- #define Q 1
- #define N 16
- int main()
- {
- int i,j,k,m,n,q,path[N],sign[N],d[N][N];
- double l=0.2,min=65535,sum,temp,P,p[N],message[N][N];
- printf("m=");
- scanf("%d",&m);//进行m轮运算
- printf("n=");
- scanf("%d",&n);//城市个数n
- for ( i = 0; i < n; i++)//城市距离矩阵d[i][j]
- {
- for ( j = 0; j < n; j++)
- {
- scanf("%d",&d[i][j]);
- message[i][j]=1;//初始化信息素矩阵message
- }
- }
- memset(p,0,sizeof(p));
- srand((unsigned)time(NULL));//初始化随机数
- for ( i = 0; i < m; i++)//每只蚂蚁的运动
- {
- for ( q = 0; q < n; q++)
- {
- memset(sign,0,sizeof(sign));//标记蚂蚁到过的城市,保证不重复
- for ( j = 0; j < n; j++)//第j次选择城市
- {
- if (j == 0)
- {
- path[0]=q;//蚂蚁的出发城市
- sign[path[0]]=1;
- continue;
- }
- sum=0;
- for ( k = 0; k < n; k++)//计算sum
- {
- if (sign[k] == 0)//没去过该城市,该城市变为候选城市
- {
- sum+=pow(message[path[j-1]][k],A)*pow(1/(double)d[path[j-1]][k],B);
- }
- }
- P=0;//总的概率系数
- for ( k = 0; k < n; k++)//计算每个候选城市的概率
- {
- if (sign[k] == 0)//如果没去过,则计算
- {
- p[k]=pow(message[path[j-1]][k],A)*pow(1/(double)d[path[j-1]][k],B)/sum;
- P+=p[k];
- }
- else//如果去过,概率是0
- {
- p[k]=0;
- }
- }
- if (P < 1)
- {
- temp=0;
- }
- else
- {
- temp=rand()%(int)P;//蚂蚁的出发城市随机生成
- }
- for ( k = 0; k < n; k++)//×××赌法,根据每个城市的概率大小,选择下一个城市
- {
- temp-=p[k];
- if (temp <= 0&&sign[k] == 0)
- {
- break;//循环结束时k即为下一个要去的城市
- }
- }
- path[j]=k;
- sign[path[j]]=1;
- }
- path[n]=path[0];
- sum=0;
- for ( k = 0; k < n; k++)
- {
- sum+=d[path[k]][path[k+1]];
- }
- if (min >= sum)//只允许在当前一直发生的所有循环中找到最优路径的蚂蚁释放信息素
- {
- min=sum;
- for ( k = 0; k < n; k++)
- {
- message[path[k]][path[k+1]]=(1-l)*message[path[k]][path[k+1]]+Q/sum;//更新信息素
- if (message[path[k]][path[k+1]] > 1)//最大最小蚂蚁系统中限定上界下界
- {
- message[path[k]][path[k+1]]=1;
- }
- else if (message[path[k]][path[k+1]] < 0.3)
- {
- message[path[k]][path[k+1]]=0.3;
- }
- }
- }
- for ( k = 0; k < n+1; k++)
- {
- printf("%d ",path[k]);
- }
- printf("%lf",sum);
- printf("\n");
- }
- }
- memset(sign,0,sizeof(sign));//标记蚂蚁到过的城市,保证不重复
- for ( i = 0; i < n; i++)//第j次选择城市
- {
- if (i == 0)
- {
- path[0]=0;//蚂蚁的出发城市
- sign[path[0]]=1;
- continue;
- }
- k=i;
- for ( j = 0; j < n; j++)
- {
- if (message[path[i-1]][j] < message[path[i-1]][k]&&sign[j] == 0)//找到信息素浓度最小的城市
- {
- k=j;
- }
- }
- path[i]=k;
- sign[path[i]]=1;
- }
- path[n]=path[0];
- sum=0;
- for ( k = 0; k < n; k++)
- {
- sum+=d[path[k]][path[k+1]];//记录最优路径长度
- }
- printf("one of the best path:\n");
- for ( k = 0; k < n; k++)//打印其中一条最优路径
- {
- printf("%d > ",path[k]);
- }
- printf("%d ",path[n]);
- printf("%lf",sum);
- printf("\n");
- for ( i = 0; i < n; i++)//打印最终的信息素浓度
- {
- for ( j = 0; j < n; j++)
- {
- printf("%lf ",message[i][j]);
- }
- printf("\n");
- }
- system("PAUSE");
- return 0;
- }