人工智能-遗传算法解决推箱子问题现实

 转自:http://blog.csdn.net/xiaofengcanyuexj/article/details/17404545

一、研究背景

   推箱子游戏中的路径查找问题—给定一方格,求两点最短距离。

   传统求两点最短路径的算法有:

     1.通用的搜索算法

     2.解决无负权边的带权有向图的单源最短路问题的Dijkstra算法

     3.求解含负权边的带权有向图的单源最短路径问题的Bellman-Ford算法

     4.Bellman-ford算法改进版快速求解单源最短路经的Shortest Path  Faster Algorithm

     …

    以上算法虽能百分之百找到最短路径,但是随着问题规模的扩大,随之而来的是组合爆炸问题,在有限的时间范围内难以求解问题。于是人们开始探索在有限时间内可以求得最优解的近似解。遗传算法求解两点最短路经就是在这样的背景下诞生的。

    遗传算法是基于生物进化原理的一种全局性优化算法,是借鉴生物的自然选择和遗传进化机制而开发出的一种全局优化自适应概率搜索算法,是生物遗传技术和计算机技术结合的产物。它采用的是启发性知识的智能搜索算法,在高空问复杂问题上比以往有更好的结果。

本题大致就是求两点的最短路径,所不同的是我们没有给定问题的解空间,即在没有给定两点可达路径的基础上求两点的最短路径。可达路径基本可以经过遗传算法演化而来。

二、组内分工

成员名

身份

分工

徐进

组长

  程序实现

熊凯平

组员

  论文撰写

黄江

组员

  算法设计

三、问题分析

给出n*m的二维方格,给定障碍物(数目及坐标),起点和终点,问绕过障碍物从起点到终点的最短路径。

基于题目,构建符合题意的模型。用户选择二维方格的行和列,即nm。然后随机生成障碍物,为求合理真实,障碍物数目应控制在一定范围内,位置既不能太稀也不能太密,起点终点随机分布。我们的设计目标是尽可能不认为干预,让箱子自己跑。

在此说明,题目虽说是推箱子,但更我们玩的推箱子游戏是有所区别的。有图为证:

          

此图是实例给出的。不考虑推的方向,在此推箱子转化为路径查找问题。

 四、算法设计

    本题核心是求两点(绕过障碍的前提下)最短的哈夫曼距离。

一个很好地解决方案是BFS,时间复杂度为(n*m),空间复杂度接近常数。下面是BFS跑出的结果

  

  本题指定用遗传算法。于是问题可以细分为两个方面分析:

1.找到从起点到终点的路径

2.在所有的路径中找到尽可能短的。

     在遗传算法中二者必须得到权衡。

本题没有用到高级的数据结构,用到了STL中的顺序容器Vector来存储每条染色体。然后开了些数组。

遗传算法 ( GA , Genetic Algorithm ) ,也称进化算法 。 遗传算法是受达尔文的进化论的启发,借鉴生物进化过程而提出的一种启发式搜索算法。

          

       我们的遗传算法通用流程框图

                  

    种群(Population):生物的进化以群体的形式进行,这样的一个群体称为种群。

  个体:组成种群的单个生物。

  基因 ( Gene ):一个遗传因子。 

  染色体 ( Chromosome ) :包含一组的基因。

  生存竞争,适者生存:对环境适应度高的、牛B的个体参与繁殖的机会比较多,后代就会越来越多。适应度低的个体参与繁殖的机会比较少,后代就会越来越少。

遗传与变异:新个体会遗传父母双方各一部分的基因,同时有一定的概率发生基因变异。

五、算法实现

    编码:需要将问题的解编码成字符串的形式才能使用遗传算法。最简单的一种编码方式是二进制编码,即将问题的解编码成二进制位数组的形式。

§ 00 = up 

§ 01 = right 

§ 10 = down 

§ 11 = left 

    每条染色体由只含01的偶数字符串组成,以上是4个基本基因片段。本题染色体是变长的(需考虑到具体题目),在不人为干预的情况下染色体所代表的运动方向是不确定的,这给问题的求解带来难度,如果染色体都过短则可能得不到路径;反之,如果染色体都过长,则可能得不到最短路径。我的方案是将染色体长度控制在[minlen,maxlen]之间,其中minlen为横坐标之差与纵坐标之差的和,maxlenn*m-numbernumber为障碍物数目)。这样基本可以保证有染色体可以进化成最短路径。所有的遗传操作的基本单位都是201串。

    适应度函数 ( Fitness Function ):用于评价种群中某个染色体的适应度,用Fitness(x)表示。本题及要找路径,还要找到最短的路径,即在从起点到目标点的可达路径都不知道的情况下的要筛选出最短的路径。这是本题面临的主要挑战。课件上给出的适应度函数如下:

         

       Fitness[i] = 1 – (distance[i] / max possible distance) 

    其中distance[i]为染色体表示运动的终点与目标点的哈夫曼距离(在不可以障碍物的情况下)。这样的适应度函数如果不做修改时很可能陷入局部最优的。如图:


    上图种群很可能找不到最优解。因为要找到最短的可达路径必须绕过去,而在绕的过程中经过上述适应度函数计算出来的适应值是很大程度上减小的。

我的解决方案是将distance[i]修改为BetDis[x][y]BetDis[x][y]表示(x,y)与目标点的考虑障碍物的最短距离。从而可以有效避免上述原因造成的过早陷入局部最优解。关于BetDis[x][y]可以通过预处理求得。通过一次BFS可以求得方格中所有点到目标点的最短距离,时间复杂度为O(n*m),空间复杂度也很低。

上述适应度度函数只能保证尽可能接近目标点,不能同时得到较短的路径。我们做了一些尝试,已知最短路径应该与目标的接近程度成正比,与路径长度成反比。我尝试将适应度函数修改为

    NewFitness[i] = a*Fitness[i]+b/len;

或  NewFitness[i] = a*Fitness[i]/len;    

  其中a,b为待定常数,len为染色体Chro[i]长度。

   但最终没有找到比较合适的ab

   于是我们还是选择了 Fitness[i] = 1 – (BetDis[x][y]/ max possible distance) 作为适应度函数。我们通过修正染色体来权衡二者。由于每条染色体都要求适应度,一个想法是在求适应度的过程中完成染色体的修正。我的修正方案有两个:

 1.若某染色体Chro[i]在运动过程中经过目标节点,则直接将Fitness[i]置为1,同时截断后面的基因片段,即缩短染色体。如:

  01 10 10 01 01 00 11 00 10 10 01 10 11 11 11 00 00 10 01

8个基因片段就到达目标点,则后面的都是有害的,于是截断,修正染色体为

  01 10 10 01 01 00 11 00 

 看似不符自然规律,但却给解题带来极大的优化。 

2.若某染色体Chro[i]在运动过程中遇到不合法状态,即走到障碍物上或越出方格,则要修正相应的基因片段,我们采用不回溯法。若当前状态不合法,则转入下一个状态,

Direction=(Direction+1)%4,其中Direction取值为0123

Direction=0,对应基因片段00

Direction=1,对应基因片段01

Direction=2,对应基因片段10

Direction=3,对应基因片段11

这样的修正方法导致染色体是可以回走的。回溯法可以避免回走,但一个长度为Size的染色体最坏的时间复杂度为O(3^size),即当前染色体所走的每一步都要回溯,这样的时间复杂度是难以接受的。所以我们选择了不回溯的。如果繁衍代数足够多,在大量交叉、变异的前提下可以降低回走的影响。

  遗传算法有3个最基本的操作:选择,交叉,变异。

选择:选择适应度高的染色体个体存活下来,淘汰适应度地的染色体个体。常用的选择策略是 比例选择,也就是个体被选中存活的概率与其适应度函数值成正比。假设群体的个体总数是PopulationSize,那么那么一个体Chro[i]被选中存活的概率为Fitness(Chro[i])/( Chro[0]+ Chro[1] + …….. + Chro[PopulationSize-1] ) 。比例选择算法可以通过轮盘赌算法”( Roulette Wheel Selection ) 实现。关于轮盘赌算法的实现在这就不多说了。

    为了防止进化过程中产生的最优解被交叉或变异所破坏,可以将每一代中的最优解原封不动的复制到下一代中,即我们采用了精英主义(Elitist Strategy)选择,这是我们采用的一种优化方案

    交叉(Crossover):基因交叉,就是把两个父体部分结构加以替换,生成新的个体的操作,本题的交叉操作比较简单,就是随机选择选择长度相同的染色体进行交叉,我们交叉的起始位置随机。如:

交叉前:

父辈1: 01 10 10 01 00 00 10 11 01 01 10 10 00 00 11 11 00 01

父辈2: 01 10 00 01 10 11 10 00 01 10 10 10 00 10 11 01 01 11

交叉后

    子辈1: 01 10 10 01 00 11 10 00 01 01 10 10 00 00 11 11 00 01

    子辈2: 01 10 00 01 10 00 10 11 01 10 10 10 00 10 11 01 01 11

所有交叉都是在交叉率CrossoverRate的控制下进行的,通过交叉率计算出当前种群的交叉数CrossoverNum

While(交叉数CrossoverNum--)

{

    随机选择等长的两条染色体;

    随机选择起始位置进行交叉;  

}

为了使程序效率不致太低,我们在交叉过程中并没有防止含非法状态的染色体产生,而是在求适应度的同时修正染色体。

    变异(Mutation):在基因交叉之后产生的子代染色体个体中,有一部分个体的某个基因片段以很小的概率发生转变,这个过程称为变异(Mutation)。我们的变异操作也变较简单,随机选择染色体,随机选择染色体变异位置,随机选择变异方向,这样可以保证过早陷入局部最优解,因为假设种群没有最优解所必需的某个基因,而选择、交叉操作不产生新基因,只有通过变异完成。如:

 变异前:10 01 01 01 10 10 11 01 11 00 11 11 11 00 11 00 10 10 01 

 变异后: 10 01 11 01 10 10 11 01 11 00 11 11 11 00 11 00 10 10 01 


    所有变异都是在变异率MutationRate的控制下进行的,通过变异率计算出当前种群的变异数MutationNum

While(变异数MutationNum--)

{

    随机选择某个染色体在随机位置向随机方向变异;  

}

    同交叉操作,为了使程序效率不致太低,我们在变异过程中并没有防止含非法状态的染色体产生,而是在求适应度的同时修正染色体。    

六、算法实现伪代码

 遗传算法伪代码GeneticAlgorithm

{

while(当前繁衍代数小于设定的繁衍代数)

{

当前繁衍代数加1

进行选择操作Selection();

进行交叉操作Crossover();

进行变异操作Mutation();

}

}

    算法的时间复杂度为O(Generation*popsize^2),在算法时间复杂度的计算过程中除去可视化时窗口延迟刷新的时间损耗;空间复杂度为O(n).

七、程序运行结果



八、参考论文



九.源程序



BFS算法实现

  1. #include<iostream>  
  2. #include<windows.h>  
  3. #include<cstdio>  
  4. #include<string>  
  5. #include<queue>  
  6. #include<ctime>  
  7. #include<gl/glut.h>  
  8. using namespace std;  
  9.   
  10. const int MAXNGRID=1000;//设置方格的总数  
  11. const int MAXN=50;//设置最大长、宽  
  12. int winHeight,winWidth;//当前窗口的长宽  
  13. bool MyLoop,SetRow,SetColumn,IsRun,First;//几个开关变量控制鼠标响应  
  14. int GridLen[2][10]=  
  15. {  
  16.     {4,6,8,10,12,14,16,18,20,22},  
  17.     {4,6,8,10,12,14,16,18,20,22}  
  18. };  
  19. int Move[4][2]={{-1,0},{1,0},{0,-1},{0,1}};  
  20.   
  21. struct state   
  22. {  
  23.     int x,y;  
  24.     string path;  
  25. }Start,Target;  
  26. queue<state>Qu;  
  27.   
  28. struct point  
  29. {  
  30.     int x,y;  
  31. };//建立方格的坐标(规则同OpenGL),便于投影到视区  
  32.   
  33. class grid  
  34. {  
  35. private :  
  36.     int Row,Column;  
  37.     int TotalPointNumber,UsedPointNumber;  
  38.     string OptimalPath;  
  39.     point Point[MAXNGRID];  
  40.     double RowInc,ColumnInc;  
  41.     bool Mark[MAXN][MAXN];//标记有没有访问  
  42. public:  
  43.     int GetRow();  
  44.     int GetColumn();  
  45.     void SetRow(int);  
  46.     void SetColumn(int);  
  47.     bool BFS();  
  48.     void DisplayGrid();  
  49.     void InitGrid();  
  50.     void DDALine(int,int,int,int);  
  51. }Grid;  
  52.   
  53. /************************************************ 
  54. *函数名GetRow 
  55. *无参数 
  56. *获得方格行数 
  57. *************************************************/  
  58. int grid::GetRow()  
  59. {  
  60.     return this->Row;  
  61. }  
  62.   
  63. /************************************************ 
  64. *函数名GetColumn 
  65. *无参数 
  66. *获得方格列数 
  67. *************************************************/  
  68. int grid::GetColumn()  
  69. {  
  70.     return this->Column;  
  71. }  
  72.   
  73. /************************************************ 
  74. *函数名SetRow 
  75. *无参数 
  76. *设置方格行数 
  77. *************************************************/  
  78. void grid::SetRow(int row)  
  79. {  
  80.     this->Row=row;  
  81. }  
  82.   
  83. /************************************************ 
  84. *函数名SetColumn 
  85. *无参数 
  86. *设置方格列数 
  87. *************************************************/  
  88. void grid::SetColumn(int column)  
  89. {  
  90.     this->Column=column;  
  91. }  
  92.   
  93. /************************************************ 
  94. *函数名BFS 
  95. *无参数 
  96. *利用广度优先寻找最短路径 
  97. *************************************************/  
  98. bool grid::BFS()  
  99. {  
  100.     state Now,Next;  
  101.     while(!Qu.empty())  
  102.         Qu.pop();  
  103.     Start.path.clear();  
  104.     Qu.push(Start);  
  105.     while(!Qu.empty())  
  106.     {  
  107.         Now=Qu.front();Qu.pop();  
  108.         if(Now.x==Target.x&&Now.y==Target.y)  
  109.         {  
  110.             this->OptimalPath=Now.path;  
  111.             cout<<OptimalPath<<endl;  
  112.             return true;  
  113.         }  
  114.         for(int i=0;i<4;i++)  
  115.         {  
  116.             int tx=Now.x+Move[i][0];   
  117.             int ty=Now.y+Move[i][1];  
  118.             if(!(tx<0||tx>=this->Row||ty<0||ty>=this->Column||Mark[tx][ty]))  
  119.             {  
  120.                 Next.x=tx;  
  121.                 Next.y=ty;  
  122.                 Next.path=Now.path;  
  123.                 /* 
  124.                 if(0==i)Next.path+='U'; 
  125.                 else if(1==i)Next.path+='D'; 
  126.                 else if(2==i)Next.path+='L'; 
  127.                 else if(3==i)Next.path+='R'; 
  128.                 this->Mark[tx][ty]=true; 
  129.                 */  
  130.                 if(0==i)Next.path+="10";  
  131.                 else if(1==i)Next.path+="00";  
  132.                 else if(2==i)Next.path+="11";  
  133.                 else if(3==i)Next.path+="01";  
  134.                 this->Mark[tx][ty]=true;  
  135.                 Qu.push(Next);  
  136.             }  
  137.         }  
  138.     }  
  139.     return false;  
  140. }  
  141.   
  142. /******************************************************* 
  143. *函数名DDALine 
  144. *无参数 
  145. *利用数值微分法由确定的两个端点画直线 
  146. ********************************************************/  
  147. void grid::DDALine(int lx1,int ly1,int lx2,int ly2)  
  148. {  
  149.     int dx,dy,epsl,k;  
  150.     float x,y,xIncre,yIncre;  
  151.     dx=lx2-lx1;   dy=ly2-ly1;  
  152.     x=lx1;        y=ly1;  
  153.     if(abs(dx)>abs(dy))  
  154.         epsl=abs(dx);  
  155.     else epsl=abs(dy);  
  156.     xIncre=(float)dx/(float)epsl;  
  157.     yIncre=(float)dy/(float)epsl;  
  158.     glBegin(GL_POINTS);//  
  159.     for(k=0;k<=epsl;k++)  
  160.     {  
  161.         glVertex2i(int(x+0.5),int(y+0.5));     
  162.         x+=xIncre;  
  163.         y+=yIncre;  
  164.     }  
  165.     glEnd();   
  166. }        
  167.   
  168. /******************************************************* 
  169. *函数名InitGrid 
  170. *无参数 
  171. *显示每局的障碍、起点、目标点 
  172. ********************************************************/  
  173. void grid::InitGrid()  
  174. {  
  175.     this->UsedPointNumber=0;  
  176.     this->TotalPointNumber=this->Row*this->Column;  
  177.     this->RowInc=winHeight/this->Row,this->ColumnInc=winWidth/this->Column;  
  178.     memset(this->Mark,false,sizeof(this->Mark));  
  179.     srand((unsigned)clock());  
  180.     do  
  181.     {  
  182.         this->UsedPointNumber=rand()%(this->TotalPointNumber);  
  183.     }while(this->UsedPointNumber>=this->TotalPointNumber/4||this->UsedPointNumber<=this->TotalPointNumber/8);  
  184.     //尽可能合理的控制障碍的数目  
  185.     int tmp=0;  
  186.     while(tmp<this->UsedPointNumber)//产生障碍的坐标并尽可能保证适当数目的障碍连成一串  
  187.     {  
  188.         int x=rand()%(this->Row),y=rand()%(this->Column),bel=rand()%2;  
  189.         if(0==bel)//(x-1,y),(x,y),(x+1,y)  
  190.         {  
  191.             if(x-1>=0)  
  192.             {  
  193.                 this->Point[tmp].y=y;this->Point[tmp].x=x-1;tmp++;  
  194.                 this->Mark[x-1][y]=true;  
  195.                 if(tmp>=this->UsedPointNumber)break;  
  196.             }  
  197.             if(x<this->Row)  
  198.             {  
  199.                 this->Point[tmp].y=y;this->Point[tmp].x=x;tmp++;  
  200.                 this->Mark[x][y]=true;  
  201.                 if(tmp>=this->UsedPointNumber)break;  
  202.             }  
  203.             if(x+1<this->Row)  
  204.             {  
  205.                 this->Point[tmp].y=y;this->Point[tmp].x=x+1;tmp++;  
  206.                 this->Mark[x+1][y]=true;  
  207.                 if(tmp>=this->UsedPointNumber)break;  
  208.             }  
  209.         }  
  210.         else //(x,y-1),(x,y),(x,y+1)  
  211.         {  
  212.             if(y-1>=0)  
  213.             {  
  214.                 this->Point[tmp].y=y-1;this->Point[tmp].x=x;tmp++;  
  215.                 this->Mark[x][y-1]=true;  
  216.                 if(tmp>=this->UsedPointNumber)break;  
  217.             }  
  218.             if(y<this->Column)  
  219.             {  
  220.                 this->Point[tmp].y=y;this->Point[tmp].x=x;tmp++;  
  221.                 this->Mark[x][y]=true;  
  222.                 if(tmp>=this->UsedPointNumber)break;  
  223.             }  
  224.             if(y+1<this->Column)  
  225.             {  
  226.                 this->Point[tmp].y=y+1;this->Point[tmp].x=x;tmp++;  
  227.                 this->Mark[x][y+1]=true;  
  228.                 if(tmp>=this->UsedPointNumber)break;  
  229.             }  
  230.         }  
  231.     }  
  232.     int sx,sy,tx,ty;  
  233.     do  
  234.     {  
  235.         do  
  236.         {  
  237.             sx=rand()%(this->Row);  
  238.             sy=rand()%(this->Column);  
  239.         }while(this->Mark[sx][sy]);//控制起点无障碍物  
  240.         do  
  241.         {  
  242.             tx=rand()%(this->Row);  
  243.             ty=rand()%(this->Column);  
  244.         }while(this->Mark[tx][ty]);//控制目标点无障碍物  
  245.     }while(abs(sx-tx)+abs(sy-ty)<(this->Row+this->Column)/3);//控制起点和目标点保持适当远的距离不小于方格任意两点最大哈夫曼距离的三分之一  
  246.     this->Mark[sx][sy]=true;  
  247.     Start.x=sx;Start.y=sy;  
  248. //  Mark[tx][ty]=true;  
  249.     Target.x=tx;Target.y=ty;  
  250.     DisplayGrid();  
  251.     if(IsRun)First=false;  
  252. }  
  253.   
  254. /******************************************************* 
  255. *函数名DisplayGrid 
  256. *无参数 
  257. *显示窗口的当前状态 
  258. ********************************************************/  
  259. void grid::DisplayGrid()  
  260. {  
  261.     int Left,Right,button,top;  
  262.     Left=0,Right=winWidth,button=0,top=winHeight;  
  263.     int lx1,ly1,lx2,ly2;  
  264.     glClear(GL_COLOR_BUFFER_BIT);  
  265.     glColor3f(0.0f,0.0f,1.0f);  
  266.     glPointSize(5);  
  267.   
  268.     //绘制放个水平线  
  269.     for(int i=0;i<=winWidth;i+=this->ColumnInc)  
  270.     {  
  271.         DDALine(Left+i,button,Left+i,top);  
  272.     }  
  273.   
  274.     //绘制放个竖直线线  
  275.     for(int i=0;i<=winHeight;i+=this->RowInc)  
  276.     {  
  277.         DDALine(Left,button+i,Right,button+i);  
  278.     }  
  279.   
  280.     //绘制障碍物  
  281.     for(int i=0;i<this->UsedPointNumber;i++)  
  282.     {  
  283.         glColor3f(1.0f,0.0f,0.0f);  
  284.         //glRectf(Left+PerRow[i]*ColumnInc,button+PerColumn[i]*RowInc,Left+PerRow[i]*ColumnInc+ColumnInc,button+PerColumn[i]*RowInc+RowInc);  
  285.           
  286.         glRectf(Left+this->Point[i].y*this->ColumnInc,button+this->Point[i].x*this->RowInc,  
  287.             Left+this->Point[i].y*this->ColumnInc+this->ColumnInc,button+this->Point[i].x*this->RowInc+this->RowInc);  
  288.     }  
  289.   
  290.     int inc=3;  
  291.     glColor3f(1.0f,1.0f,0.0f);  
  292.     glRectf(Left+Start.y*this->ColumnInc+inc,button+Start.x*this->RowInc+inc,  
  293.         Left+Start.y*this->ColumnInc+this->ColumnInc-inc,button+Start.x*this->RowInc+this->RowInc-inc);  
  294.   
  295.     glColor3f(1.0f,.0f,1.0f);  
  296.     glRectf(Left+Target.y*this->ColumnInc+inc,button+Target.x*this->RowInc+inc,  
  297.         Left+Target.y*this->ColumnInc+this->ColumnInc-inc,button+Target.x*this->RowInc+this->RowInc-inc);  
  298.   
  299.     if(!First)//不是第一次初始化窗口,则会出现相应染色体对应的路径  
  300.     {  
  301.         int tcnt=this->UsedPointNumber;  
  302.         BFS();  
  303.         int size=this->OptimalPath.size();  
  304.         int tx=Start.x,ty=Start.y;  
  305.         for(int i=0;i<size-1;i++)  
  306.         {  
  307.             if(this->OptimalPath[i]=='D')  
  308.             {  
  309.                 tx=tx+1;ty=ty;  
  310.             }  
  311.             else if(this->OptimalPath[i]=='U')  
  312.             {  
  313.                 tx=tx-1;ty=ty;  
  314.             }  
  315.             else if(this->OptimalPath[i]=='L')  
  316.             {  
  317.                 tx=tx;ty=ty-1;  
  318.             }  
  319.             else if(this->OptimalPath[i]=='R')  
  320.             {  
  321.                 tx=tx;ty=ty+1;  
  322.             }  
  323.             this->Point[this->UsedPointNumber].x=tx;this->Point[this->UsedPointNumber].y=ty;  
  324.             this->UsedPointNumber++;  
  325.         }  
  326.         for(int j=tcnt;j<this->UsedPointNumber;j++)  
  327.         {  
  328.             glColor3f(0.0f,1.0f,0.0f);  
  329.             glRectf(Left+this->Point[j].y*this->ColumnInc,button+this->Point[j].x*this->RowInc,  
  330.                 Left+this->Point[j].y*this->ColumnInc+this->ColumnInc,button+this->Point[j].x*this->RowInc+this->RowInc);  
  331.         }  
  332.         this->UsedPointNumber=tcnt;  
  333.     }  
  334.     glFlush();  
  335. }  
  336.   
  337.   
  338.   
  339. /******************************************************* 
  340. *函数名init 
  341. *无参数 
  342. *初始化函数 
  343. ********************************************************/  
  344. void init()  
  345. {  
  346.     glClearColor(0.0f,0.0f,0.0f,1.0f);  
  347.     glMatrixMode(GL_PROJECTION);    //设置投影参数  
  348.     gluOrtho2D(0.0f, 1000.0f,0.0f,600.0f);  
  349.     MyLoop=false;  
  350.     SetRow=false;SetColumn=false;  
  351.     IsRun=false;  
  352.     First=true;  
  353. }  
  354.   
  355.   
  356.   
  357. /******************************************************* 
  358. *函数名Display() 
  359. *无参数 
  360. *窗口创建时显示背景色 
  361. ********************************************************/  
  362. void Display()  
  363. {  
  364.     glClear(GL_COLOR_BUFFER_BIT);  
  365.     glFlush();  
  366. }  
  367.   
  368.   
  369. /******************************************************* 
  370. *函数名ChangeSize 
  371. *无参数 
  372. *窗口发生变化时完成初始化 
  373. ********************************************************/  
  374. void ChangeSize(int w, int h)  
  375. {     
  376.     winWidth=w;winHeight=h;  
  377.     glViewport(0, 0, w, h);                
  378.     glMatrixMode(GL_PROJECTION);        
  379.     glLoadIdentity();             
  380.     gluOrtho2D(0.0,winWidth,0.0,winHeight);  
  381. }  
  382.   
  383. /******************************************************* 
  384. *函数名timer 
  385. *无关参数 
  386. *定期刷新窗口 
  387. ********************************************************/  
  388. void Timer(int p)  
  389. {  
  390.     Grid.DisplayGrid();  
  391. }  
  392.   
  393. /******************************************************* 
  394. *函数名MousePlot 
  395. *4个参数:按键类型、动作、对应的坐标 
  396. *鼠标响应函数 
  397. ********************************************************/  
  398. void MousePlot(int button,int action,int x,int y)  
  399. {  
  400.     if(SetRow&&SetColumn)  
  401.     {  
  402.         if(button==GLUT_LEFT_BUTTON&&action==GLUT_DOWN)   
  403.         {     
  404.             if(!MyLoop&&!IsRun)  
  405.                 Grid.InitGrid();  
  406.             else MyLoop=false;  
  407.         }  
  408.         else if(button==GLUT_MIDDLE_BUTTON&&action==GLUT_DOWN)  
  409.         {  
  410.             MyLoop=true;  
  411.             IsRun=true;  
  412.             First=false;  
  413.             glutTimerFunc(200,Timer,0);   
  414.         }  
  415.     }  
  416. }  
  417.   
  418. /******************************************************* 
  419. *函数名ProcessMenu 
  420. *一个参数,菜单选项 
  421. *菜单响应函数 
  422. ********************************************************/  
  423. void ProcessMenu(int value)  
  424. {  
  425.     if(IsRun)//在运行过程中重置方格  
  426.     {  
  427.         SetRow=false;  
  428.         SetColumn=false;  
  429.         IsRun=false;  
  430.         First=true;  
  431.         MyLoop=false;  
  432.     }  
  433.     if(value<=10)  
  434.     {  
  435.         Grid.SetRow(GridLen[0][value-1]);  
  436.         SetRow=true;  
  437.     }  
  438.     else if(value<=20)  
  439.     {  
  440.         Grid.SetColumn(GridLen[1][value-11]);  
  441.         SetColumn=true;  
  442.     }  
  443. }  
  444.   
  445.   
  446. /******************************************************* 
  447. *函数名MyCreateMenu 
  448. *无菜单 
  449. *初始化菜单 
  450. ********************************************************/  
  451. void MyCreateMenu()  
  452. {  
  453.     int SetWidth=glutCreateMenu(ProcessMenu);  
  454.     glutAddMenuEntry("4",1);  
  455.     glutAddMenuEntry("6",2);  
  456.     glutAddMenuEntry("8",3);  
  457.     glutAddMenuEntry("10",4);  
  458.     glutAddMenuEntry("12",5);  
  459.     glutAddMenuEntry("14",6);  
  460.     glutAddMenuEntry("16",7);  
  461.     glutAddMenuEntry("18",8);  
  462.     glutAddMenuEntry("20",9);  
  463.     glutAddMenuEntry("22",10);  
  464.     int SetHeight=glutCreateMenu(ProcessMenu);  
  465.     glutAddMenuEntry("4",11);  
  466.     glutAddMenuEntry("6",12);  
  467.     glutAddMenuEntry("8",13);  
  468.     glutAddMenuEntry("10",14);  
  469.     glutAddMenuEntry("12",15);  
  470.     glutAddMenuEntry("14",16);  
  471.     glutAddMenuEntry("16",17);  
  472.     glutAddMenuEntry("18",18);  
  473.     glutAddMenuEntry("20",19);  
  474.     glutAddMenuEntry("22",20);  
  475.     int Choice=glutCreateMenu(ProcessMenu);  
  476.     glutAddSubMenu("水平方向方格数",SetWidth);  
  477.     glutAddSubMenu("垂直方向方格数",SetHeight);  
  478.     glutCreateMenu(ProcessMenu);  
  479.     glutAddSubMenu("设置",Choice);  
  480.     glutAttachMenu(GLUT_RIGHT_BUTTON);  
  481. }  
  482.   
  483.   
  484. int main(int argc, char *argv[])  
  485. {     
  486.     glutInit(&argc,argv);  
  487.     glutInitDisplayMode(GLUT_RGB|GLUT_SINGLE);  
  488.     glutInitWindowPosition(0, 0);  
  489.     glutInitWindowSize(1000, 600);  
  490.     glutCreateWindow("BFS算法在方格中的求最短路径动画演示");  
  491.     glutDisplayFunc(Display);  
  492.     glutReshapeFunc(ChangeSize);  
  493.     glutMouseFunc(MousePlot);  
  494.     MyCreateMenu();  
  495.     init();  
  496.     glutMainLoop();       
  497.     return 0;  
  498. }  




用BFS引导的

  1. #include<windows.h>  
  2. #include<gl/glut.h>   
  3. #include<iostream>  
  4. #include<string>  
  5. #include<vector>  
  6. #include<cstdio>  
  7. #include<cstring>  
  8. #include<cmath>  
  9. #include<cstdlib>  
  10. #include<ctime>  
  11. #include<iomanip>  
  12. #include<map>  
  13. #include<algorithm>  
  14. #include<queue>  
  15. using namespace std;  
  16.   
  17. const int MAXNGRID=1000;//设置方格的总数  
  18. const int MAXROC=50;//设置最大长、宽  
  19. const int MAXCHRO=250;//染色体条数  
  20. const double eps=1e-10;  
  21.   
  22. int winHeight,winWidth;//当前窗口的长宽  
  23. bool MyLoop,SetRow,SetColumn,IsRun,First;//几个开关变量控制鼠标响应  
  24. int GridLen[2][10]=  
  25. {  
  26.     {4,6,8,10,12,14,16,18,20,22},  
  27.     {4,6,8,10,12,14,16,18,20,22}  
  28. };  
  29. int Move[4][2]={{-1,0},{1,0},{0,-1},{0,1}};  
  30.   
  31. struct state   
  32. {  
  33.     int x,y;  
  34.     int dis;  
  35.     string path;  
  36. }Start,Target;  
  37. queue<state>Qu;  
  38.   
  39. struct point  
  40. {  
  41.     int x,y;  
  42. };//建立方格的坐标(规则同OpenGL),便于投影到视区  
  43.   
  44. map<int,string>Mat;  
  45.   
  46. void InitMap()  
  47. {  
  48.     Mat[0]="00";Mat[1]="01";Mat[2]="10";Mat[3]="11";  
  49. }  
  50.   
  51. class grid  
  52. {  
  53. private :  
  54.     int Row,Column; //方格的行列  
  55.     int TotalPointNumber,UsedPointNumber;      //总的点数、已用点数  
  56.     int GenerationNum,PopulationSize,MaxDis,MinDis;//繁殖代数、种群规模、最大距离、最短距离  
  57.     int BetDis[MAXROC][MAXROC];//BetDis[x][y]表示(x,y)到目标点的最短距离  
  58.     int tcnt;           //全局临时变量  
  59.     string OptimalPath;//遗传算法求得的最短路径  
  60.     string BFSPath;    //BFS算法最短路径  
  61.     double OptimalFitness;//已找到的最短路径  
  62.     point Point[MAXNGRID];  //待打印的点  
  63.     double RowInc,ColumnInc; //窗口的行列步长  
  64.     bool Mark[MAXROC][MAXROC];//标记有没有访问  
  65.     double MutationRate;      //变异率  
  66.     double CrossoverRate;     //杂交率  
  67.     double MutationNum;       //当代变异个数  
  68.     double CrossoverNum;       //当代交叉个数  
  69.     int now_Gen;              //当前代数  
  70.     double Fitness[MAXCHRO];   //适应度  
  71.     double Random[MAXCHRO];    //产生的随机数  
  72.     double ProSec[MAXCHRO];    //选择概率  
  73.     double ProAccu[MAXCHRO];  //累积选择概率  
  74.     vector<string>Chro;      //染色体  
  75.     bool IsUsed[MAXCHRO];//标记当前繁殖代数下该染色体是否已经交叉或变异过  
  76. public:  
  77.     int GetRow();  
  78.     int GetColumn();  
  79.     void SetRow(int);  
  80.     void SetColumn(int);  
  81.     bool BFS1();  
  82.     bool BFS2();  
  83.     void DisplayGrid();  
  84.     void InitGrid();  
  85.     void DDALine(int,int,int,int);  
  86.     void GetMinMaxDis();  
  87.     bool IsBump(int,int);  
  88.     bool GetNext(int &,int &,int);  
  89.     int RunRoute(int &,int &,string &);  
  90.     double GetFitness(string &);  
  91.     void Manu_Init();  
  92.     int GetRand(int);  
  93.     void Mutation();  
  94.     void My_Rand();  
  95.     void Get_Sec_num();  
  96.     void Selection();  
  97.     void GetCros(int,int,int,int);  
  98.     void Crossover();  
  99.     friend void Timer(int);  
  100.     friend void MousePlot(int,int,int,int);  
  101. }Grid;  
  102.   
  103. /************************************************ 
  104. *函数名GetRow 
  105. *无参数 
  106. *获得方格行数 
  107. *************************************************/  
  108. int grid::GetRow()  
  109. {  
  110.     return this->Row;  
  111. }  
  112.   
  113. /************************************************ 
  114. *函数名GetColumn 
  115. *无参数 
  116. *获得方格列数 
  117. *************************************************/  
  118. int grid::GetColumn()  
  119. {  
  120.     return this->Column;  
  121. }  
  122.   
  123. /************************************************ 
  124. *函数名SetRow 
  125. *无参数 
  126. *设置方格行数 
  127. *************************************************/  
  128. void grid::SetRow(int row)  
  129. {  
  130.     this->Row=row;  
  131. }  
  132.   
  133. /************************************************ 
  134. *函数名SetColumn 
  135. *无参数 
  136. *设置方格列数 
  137. *************************************************/  
  138. void grid::SetColumn(int column)  
  139. {  
  140.     this->Column=column;  
  141. }  
  142.   
  143. /****************************************************************************** 
  144. *函数名GetMinMaxDis 
  145. *无参数          
  146. *计算路径可能的最小距离和最大距离 
  147. *******************************************************************************/  
  148. void grid::GetMinMaxDis()  
  149. {  
  150.     this->MaxDis=(this->Row)*(this->Column);  
  151.     this->MinDis=abs(Target.x-Start.x)+abs(Target.y-Start.y);  
  152. }  
  153.   
  154. /****************************************************************************** 
  155. *函数名IsBump 
  156. *两个参数分别表示横坐标、纵坐标          
  157. *判断当前是否合法,及是否撞墙或越界 
  158. *******************************************************************************/  
  159. bool grid::IsBump(int tRow,int tColumn)  
  160. {  
  161.     if(tRow<0||tRow>=this->Row||tColumn<0||tColumn>=this->Column||this->Mark[tRow][tColumn])  
  162.         return true;  
  163.     return false;  
  164. }  
  165.   
  166. /****************************************************************************** 
  167. *函数名GetNext 
  168. *当前的坐标,移动方向        
  169. *若下一个是合法状态,移到该状态,返回true;否则不做操作返回false 
  170. *******************************************************************************/  
  171. bool grid::GetNext(int &tRow,int &tColumn,int tDirection)  
  172. {  
  173.     int incx,incy;  
  174.     if(0==tDirection)          incx=1,incy= 0;  
  175.     else if(1==tDirection)     incx= 0,incy= 1;  
  176.     else if(2==tDirection)     incx= -1,incy= 0;  
  177.     else                       incx= 0,incy=-1;  
  178.     if(!(this->IsBump(tRow+incx,tColumn+incy)))  
  179.     {  
  180.         tRow=tRow+incx,tColumn=tColumn+incy;  
  181.         return true;//当前方向有效  
  182.     }  
  183.     return false;//当前方向无效  
  184. }  
  185.   
  186.   
  187. /****************************************************************************** 
  188. *函数名:RunRoute 
  189. *3个参数分别表示当前点的坐标,和当前处理染色体的引用         
  190. * 寻找并记录染色体对应的有效路径同时修改不合法的染色体 
  191. *******************************************************************************/  
  192. int grid::RunRoute(int &tRow,int &tColumn,string &Chromosome)  
  193. {  
  194.     int size=Chromosome.size();  
  195.     int Direction;  
  196.     int len=1;  
  197.     string newchro;  
  198.     string tmp;  
  199.     for(int i=0;i<size;i+=2)  
  200.     {  
  201.         tmp.clear();  
  202.         tmp+=Chromosome[i];  
  203.         tmp+=Chromosome[i+1];  
  204.         if(tmp=="00")  
  205.         {  
  206.             Direction=0;  
  207.         }  
  208.         else if(tmp=="01")  
  209.         {  
  210.             Direction=1;  
  211.         }  
  212.         else if(tmp=="10")  
  213.         {  
  214.             Direction=2;  
  215.         }  
  216.         else  
  217.         {  
  218.             Direction=3;  
  219.         }  
  220.         int tR=tRow,tC=tColumn;  
  221.         while(!this->GetNext(tRow,tColumn,Direction))  
  222.             //当前方向不合法,则转到下一方向;如果除去来的其他3个方向都不合法,则返回当前位置的前一个位置  
  223.                 //此处最好的方法是回溯法,类比深搜,但时间复杂度是不能接受的,最坏可达O(4^n)  
  224.         {  
  225.             Direction=(Direction+1)%4;  
  226.             tmp=Mat[Direction];  
  227.         }  
  228.         Chromosome[i]=tmp[0];//修正染色体  
  229.         Chromosome[i+1]=tmp[1];  
  230.         newchro+=tmp;  
  231.         if(tRow==Target.x&&tColumn==Target.y)  
  232.         {  
  233.             Chromosome=newchro;//找到目标点也做修改染色体,保证路径尽可能短  
  234.             return len;  
  235.         }  
  236.         this->Point[this->UsedPointNumber].x=tRow;  
  237.         this->Point[this->UsedPointNumber].y=tColumn;  
  238.         this->UsedPointNumber++;  
  239.         len++;  
  240.     }  
  241.     return len;  
  242. }  
  243.   
  244. /****************************************************************************** 
  245. *函数名GetFitness 
  246. *一个参数为当前处理染色体的引用         
  247. *计算个体适应度 
  248. *******************************************************************************/  
  249. double grid::GetFitness(string &Chromosome)  
  250. {  
  251.     int Row=Start.x,Column=Start.y;  
  252.     int len=this->RunRoute(Row,Column,Chromosome);  
  253.     if(Row==Target.x&&Column==Target.y)  
  254.     {  
  255.         return 1.0;  
  256.     }  
  257.     //double tmpdis=abs(Target.x-Row)+abs(Target.y-Column);  
  258.     double tmpdis=this->BetDis[Row][Column];//此时tmpdis表示到目标点的最短路径长  
  259.     double ret=1-tmpdis/(this->MaxDis);  
  260.     //double ret=1.0*(1-tmpdis/MaxDis)+1.0/len;//保证len不为0  
  261.     return ret;  
  262. }  
  263.   
  264. /****************************************************************************** 
  265. *函数名ChromosomeCmp 
  266. *两个参数,分别表示两条染色体       
  267. *依据长度从小到大对染色体进行排序,方便交叉 
  268. *******************************************************************************/  
  269. bool ChromosomeCmp(string tmpa,string tmpb)  
  270. {  
  271.     return tmpa.size()<tmpb.size();  
  272. }  
  273.   
  274. /****************************************************************************** 
  275. *函数名Manu_Init 
  276. *无参数           
  277. *随机初始化种群 
  278. 难点在于染色体长度和表征的路径的控制,在此我没有找到对应随机游戏局面的比较好的初始化方案 
  279. 原因在于局面是随机任意的,且找路径的个体是看不知全局的,只能随便跑,我认为人为干预是不恰当的 
  280. *******************************************************************************/  
  281. void grid::Manu_Init()  
  282. {  
  283.     this->Chro.clear();  
  284.     this->GetMinMaxDis();         //获得最大值、最小值  
  285.     int minlen=this->MinDis;  
  286.     int maxlen=((this->MaxDis)-(this->UsedPointNumber))/3;  
  287.     this->PopulationSize=200;///  
  288.     this->GenerationNum=1000;  
  289.     srand((unsigned)clock());  
  290.     string tmp;  
  291.     for(int i=0;i<this->PopulationSize;i++)  
  292.     {  
  293.         tmp.clear();  
  294.         int len;  
  295.         do  
  296.         {  
  297.             len=rand()%maxlen;  
  298.             if(len%2)len++;//保证染色体长度为偶数  
  299.         }while(len<minlen);//控制染色体长度在[minlen,maxlen)之间  
  300.         while(len)  
  301.         {  
  302.             int id=rand()%4;  
  303.             tmp+=Mat[id];  
  304.             len--;  
  305.         }  
  306.         (this->Chro).push_back(tmp);  
  307.     }  
  308.     this->OptimalPath=this->Chro[0];  
  309.     this->OptimalFitness=0;  
  310.     this->CrossoverRate=0.5;  
  311.     this->MutationRate=0.05;  
  312. }  
  313.   
  314. /****************************************************************************** 
  315. *函数名GetRand 
  316. *一个参数,表示上限          
  317. *返回【0,len)的随机数 
  318. *******************************************************************************/  
  319. int grid::GetRand(int len)  
  320. {  
  321.     double be=1.0/(len);  
  322.     double Rand=1.0*rand()/(RAND_MAX);  
  323.     int ret=(int)(Rand/be);  
  324.     if(ret>=len)ret--;  
  325.     return ret;  
  326. }  
  327.   
  328. /****************************************************************************** 
  329. *函数名Mutation() 
  330. * 无参数         
  331. *随机选染色体,再随机选一个基因片段变异,变异方向不确定 
  332. *******************************************************************************/  
  333. void grid::Mutation()  
  334. {  
  335.     int belong,id,to,size=this->Chro.size();  
  336.     string tmp;  
  337.     srand((unsigned)clock());  
  338.     memset(this->IsUsed,0,sizeof(this->IsUsed));  
  339.     while(this->MutationNum>1)  
  340.     {  
  341.         do  
  342.         {  
  343.             do  
  344.             {  
  345.                 belong=this->GetRand(size);//属于哪个染色体  
  346.             }while(this->IsUsed[belong]);//选择当前代没变异过的  
  347.             id=this->GetRand(this->Chro[belong].size()/2);//变异那个片段  
  348.             to=GetRand(4);  
  349.             tmp.clear();  
  350.             tmp=this->Chro[belong];  
  351.             tmp[id*2]=Mat[to][0];  
  352.             tmp[id*2+1]=Mat[to][1];  
  353.         }while(tmp==this->Chro[belong]);//保证变异后与原来不同  
  354.         this->Chro[belong]=tmp;  
  355.         this->MutationNum-=1;  
  356.     }  
  357. }  
  358.   
  359. /****************************************************************************** 
  360. *函数名My_Rand 
  361. *无参数          
  362. *产生一组[0,1]内的分布均匀的随机数 
  363. *******************************************************************************/  
  364. void grid::My_Rand()  
  365. {  
  366.     srand((unsigned)clock());  
  367.     int size=this->Chro.size();  
  368.     for(int i=0;i<size;i++)  
  369.     {  
  370.         this->Random[i]=1.0*rand()/RAND_MAX;  
  371.     }  
  372. }  
  373.   
  374.   
  375. /****************************************************************************** 
  376. *函数名Get_Sec_num 
  377. *无参数          
  378. *利用赌轮选择法选择适应度大的生存下来 
  379. *******************************************************************************/  
  380. void grid::Get_Sec_num()  
  381. {  
  382.     this->My_Rand();  
  383.     vector<string>TmpChromosome;  
  384.     int j=0;  
  385.     int size=this->Chro.size();  
  386.     while(j<size)  
  387.     {  
  388.         int i;  
  389.         for(i=1;i<=size;i++)  
  390.         {  
  391.             if(this->Random[j]<=this->ProAccu[i]+eps)//防止浮点数误差  
  392.             {  
  393.                 TmpChromosome.push_back(this->Chro[i-1]);  
  394.                 j++;  
  395.                 break;  
  396.             }  
  397.         }  
  398.     }  
  399.     for(int i=0;i<size;i++)  
  400.         this->Chro[i]=TmpChromosome[i];  
  401.     TmpChromosome.clear();  
  402. }  
  403.   
  404. /****************************************************************************** 
  405. *函数名 
  406. *无参数         
  407. *遗传操作-选择主函数 
  408. *******************************************************************************/  
  409. void grid::Selection()  
  410. {  
  411.     int size=this->Chro.size();  
  412.     double sum=0;  
  413.     this->OptimalFitness=0;  
  414.     this->OptimalPath.clear();  
  415.     for(int i=0;i<size;i++)  
  416.     {  
  417.         sum+=this->Fitness[i];  
  418.         if(this->Fitness[i]>this->OptimalFitness||((fabs(this->Fitness[i]-this->OptimalFitness)<=eps)&&this->OptimalPath.size()>this->Chro[i].size()))  
  419.         {  
  420.             this->OptimalFitness=this->Fitness[i];  
  421.             this->OptimalPath=this->Chro[i];  
  422.         }  
  423.     }  
  424.     for(int i=1;i<=size;i++)  
  425.     {  
  426.         this->ProSec[i]=this->Fitness[i-1]/sum;  
  427.     }  
  428.     this->ProAccu[0]=0;  
  429.     for(int i=1;i<=size;i++)  
  430.         this->ProAccu[i]=this->ProAccu[i-1]+this->ProSec[i];  
  431.     this->Get_Sec_num();  
  432. }  
  433.   
  434. /****************************************************************************** 
  435. *函数名GetCros 
  436. *4个参数,分别表示带交叉的两条染色体的下标,以及对应的交叉位置    
  437. *功能遗传操作-交叉函数 
  438. *******************************************************************************/  
  439. void grid::GetCros(int One,int Two,int From,int To)  
  440. {  
  441.     string tmp;  
  442.     for(int i=From;i<=To;i++)  
  443.     {  
  444.         tmp.clear();  
  445.         tmp+=this->Chro[One][i*2];  
  446.         tmp+=this->Chro[One][i*2+1];  
  447.         this->Chro[One][i*2]=this->Chro[Two][i*2];  
  448.         this->Chro[One][i*2+1]=this->Chro[Two][i*2+1];  
  449.         this->Chro[Two][i*2]=tmp[0];  
  450.         this->Chro[Two][i*2+1]=tmp[1];  
  451.     }  
  452. }  
  453.   
  454. /****************************************************************************** 
  455. *函数名Crossover 
  456. *无参数  
  457. *功能遗传操作-交叉主函数,选择相同长度的染色体进行交叉 
  458. *******************************************************************************/  
  459. void grid::Crossover()  
  460. {  
  461.     sort(this->Chro.begin(),this->Chro.end(),ChromosomeCmp);  
  462.     int id,id1,id2,size=this->Chro.size();  
  463.     bool flag;  
  464.     memset(this->IsUsed,0,sizeof(this->IsUsed));  
  465.     while(this->CrossoverNum>1.0)  
  466.     {  
  467.         flag=false;  
  468.         do  
  469.         {  
  470.             id=this->GetRand(size);  
  471.         }while(this->IsUsed[id]);//选择没交叉过的染色体  
  472.         int tsize=(this->Chro[id]).size();  
  473.   
  474.         ///////选择长度相同且没交叉过的染色体  
  475.         if(id!=0&&!(this->IsUsed[id-1])&&tsize==this->Chro[id-1].size())  
  476.         {  
  477.             flag=true;  
  478.             do  
  479.             {  
  480.                 id1=this->GetRand(tsize/2);  
  481.                 id2=this->GetRand(tsize/2);  
  482.             }while(id1>id2);  
  483.             this->GetCros(id,id-1,id1,id2);  
  484.         }  
  485.         if(!flag&&id!=size-1&&!(this->IsUsed[id+1])&&tsize==this->Chro[id+1].size())  
  486.         {  
  487.             flag=true;  
  488.             do  
  489.             {  
  490.                 id1=this->GetRand(tsize/2);  
  491.                 id2=this->GetRand(tsize/2);  
  492.             }while(id1>id2);  
  493.             this->GetCros(id,id+1,id1,id2);  
  494.         }  
  495.         if(flag)this->CrossoverNum-=1;  
  496.     }  
  497. }  
  498.   
  499. /************************************************ 
  500. *函数名BFS 
  501. *无参数 
  502. *利用广度优先预处理所有的点到目标点的最近距离 
  503. *************************************************/  
  504. bool grid::BFS1()  
  505. {  
  506.     state Now,Next;  
  507.     while(!Qu.empty())  
  508.         Qu.pop();  
  509.     Qu.push(Target);  
  510.     Target.dis=0;  
  511.     bool Visited[MAXROC][MAXROC];  
  512.     memcpy(Visited,Mark,sizeof(Mark));  
  513.     Visited[Target.x][Target.y]=true;  
  514.     while(!Qu.empty())  
  515.     {  
  516.         Now=Qu.front();Qu.pop();  
  517.         for(int i=0;i<4;i++)  
  518.         {  
  519.             int tx=Now.x+Move[i][0];   
  520.             int ty=Now.y+Move[i][1];  
  521.             int dis=Now.dis+1;  
  522.             if(!(tx<0||tx>=this->Row||ty<0||ty>=this->Column||Visited[tx][ty]))  
  523.             {  
  524.                 Next.x=tx;  
  525.                 Next.y=ty;  
  526.                 Next.dis=dis;  
  527.                 this->BetDis[tx][ty]=dis;  
  528.                 Visited[tx][ty]=true;  
  529.                 Qu.push(Next);  
  530.             }  
  531.         }  
  532.     }  
  533.     return false;  
  534. }  
  535.   
  536.   
  537. /************************************************ 
  538. *函数名BFS 
  539. *无参数 
  540. *利用广度优先寻找最短路径 
  541. *************************************************/  
  542. bool grid::BFS2()  
  543. {  
  544.     state Now,Next;  
  545.     while(!Qu.empty())  
  546.         Qu.pop();  
  547.     Start.path.clear();  
  548.     bool Visited[MAXROC][MAXROC];  
  549.     memcpy(Visited,Mark,sizeof(Mark));  
  550.     Visited[Target.x][Target.y]=false;  
  551.     Visited[Start.x][Start.y]=true;  
  552.     Qu.push(Start);  
  553.     while(!Qu.empty())  
  554.     {  
  555.         Now=Qu.front();Qu.pop();  
  556.         if(Now.x==Target.x&&Now.y==Target.y)  
  557.         {  
  558.             this->OptimalPath=Now.path;  
  559.             this->OptimalFitness=1.0;  
  560.             return true;  
  561.         }  
  562.         for(int i=0;i<4;i++)  
  563.         {  
  564.             int tx=Now.x+Move[i][0];   
  565.             int ty=Now.y+Move[i][1];  
  566.             if(!(tx<0||tx>=this->Row||ty<0||ty>=this->Column||Visited[tx][ty]))  
  567.             {  
  568.                 Next.x=tx;  
  569.                 Next.y=ty;  
  570.                 Next.path=Now.path;  
  571.                   
  572.                 if(0==i)Next.path+="10";  
  573.                 else if(1==i)Next.path+="00";  
  574.                 else if(2==i)Next.path+="11";  
  575.                 else if(3==i)Next.path+="01";  
  576.                 Visited[tx][ty]=true;  
  577.                 Qu.push(Next);  
  578.             }  
  579.         }  
  580.     }  
  581.     return false;  
  582. }  
  583.   
  584.   
  585. /******************************************************* 
  586. *函数名DDALine 
  587. *无参数 
  588. *利用数值微分法由确定的两个端点画直线 
  589. ********************************************************/  
  590. void grid::DDALine(int lx1,int ly1,int lx2,int ly2)  
  591. {  
  592.     int dx,dy,epsl,k;  
  593.     float x,y,xIncre,yIncre;  
  594.     dx=lx2-lx1;   dy=ly2-ly1;  
  595.     x=lx1;        y=ly1;  
  596.     if(abs(dx)>abs(dy))  
  597.         epsl=abs(dx);  
  598.     else epsl=abs(dy);  
  599.     xIncre=(float)dx/(float)epsl;  
  600.     yIncre=(float)dy/(float)epsl;  
  601.     glBegin(GL_POINTS);//  
  602.     for(k=0;k<=epsl;k++)  
  603.     {  
  604.         glVertex2i(int(x+0.5),int(y+0.5));     
  605.         x+=xIncre;  
  606.         y+=yIncre;  
  607.     }  
  608.     glEnd();   
  609. }        
  610.   
  611. /******************************************************* 
  612. *函数名InitGrid 
  613. *无参数 
  614. *显示每局的障碍、起点、目标点 
  615. ********************************************************/  
  616. void grid::InitGrid()  
  617. {  
  618.     this->UsedPointNumber=0;  
  619.     this->TotalPointNumber=this->Row*this->Column;  
  620.     this->RowInc=winHeight/this->Row,this->ColumnInc=winWidth/this->Column;  
  621.     memset(this->Mark,false,sizeof(this->Mark));  
  622.     srand((unsigned)clock());  
  623.     do  
  624.     {  
  625.         this->UsedPointNumber=rand()%(this->TotalPointNumber);  
  626.     }while(this->UsedPointNumber>=this->TotalPointNumber/4||this->UsedPointNumber<=this->TotalPointNumber/8);  
  627.     //尽可能合理的控制障碍的数目  
  628.     int tmp=0;  
  629.     while(tmp<this->UsedPointNumber)//产生障碍的坐标并尽可能保证适当数目的障碍连成一串  
  630.     {  
  631.         int x=rand()%(this->Row),y=rand()%(this->Column),bel=rand()%2;  
  632.         if(0==bel)//(x-1,y),(x,y),(x+1,y)  
  633.         {  
  634.             if(x-1>=0)  
  635.             {  
  636.                 this->Point[tmp].y=y;this->Point[tmp].x=x-1;tmp++;  
  637.                 this->Mark[x-1][y]=true;  
  638.                 if(tmp>=this->UsedPointNumber)break;  
  639.             }  
  640.             if(x<this->Row)  
  641.             {  
  642.                 this->Point[tmp].y=y;this->Point[tmp].x=x;tmp++;  
  643.                 this->Mark[x][y]=true;  
  644.                 if(tmp>=this->UsedPointNumber)break;  
  645.             }  
  646.             if(x+1<this->Row)  
  647.             {  
  648.                 this->Point[tmp].y=y;this->Point[tmp].x=x+1;tmp++;  
  649.                 this->Mark[x+1][y]=true;  
  650.                 if(tmp>=this->UsedPointNumber)break;  
  651.             }  
  652.         }  
  653.         else //(x,y-1),(x,y),(x,y+1)  
  654.         {  
  655.             if(y-1>=0)  
  656.             {  
  657.                 this->Point[tmp].y=y-1;this->Point[tmp].x=x;tmp++;  
  658.                 this->Mark[x][y-1]=true;  
  659.                 if(tmp>=this->UsedPointNumber)break;  
  660.             }  
  661.             if(y<this->Column)  
  662.             {  
  663.                 this->Point[tmp].y=y;this->Point[tmp].x=x;tmp++;  
  664.                 this->Mark[x][y]=true;  
  665.                 if(tmp>=this->UsedPointNumber)break;  
  666.             }  
  667.             if(y+1<this->Column)  
  668.             {  
  669.                 this->Point[tmp].y=y+1;this->Point[tmp].x=x;tmp++;  
  670.                 this->Mark[x][y+1]=true;  
  671.                 if(tmp>=this->UsedPointNumber)break;  
  672.             }  
  673.         }  
  674.     }  
  675.     int sx,sy,tx,ty;  
  676.     do  
  677.     {  
  678.         do  
  679.         {  
  680.             sx=rand()%(this->Row);  
  681.             sy=rand()%(this->Column);  
  682.         }while(this->Mark[sx][sy]);//控制起点无障碍物  
  683.         do  
  684.         {  
  685.             tx=rand()%(this->Row);  
  686.             ty=rand()%(this->Column);  
  687.         }while(this->Mark[tx][ty]);//控制目标点无障碍物  
  688.     }while(abs(sx-tx)+abs(sy-ty)<(this->Row+this->Column)/3);//控制起点和目标点保持适当远的距离不小于方格任意两点最大哈夫曼距离的三分之一  
  689.     this->Mark[sx][sy]=true;  
  690.     Start.x=sx;Start.y=sy;  
  691.     //this->Mark[tx][ty]=true;  
  692.     Target.x=tx;Target.y=ty;  
  693.     this->Manu_Init();  
  694.     this->DisplayGrid();  
  695.     this->BFS1();  
  696.     this->BFS2();  
  697.     if(IsRun)First=false;  
  698.     if(IsRun)First=false;  
  699. }  
  700.   
  701. /******************************************************* 
  702. *函数名DisplayGrid 
  703. *无参数 
  704. *显示窗口的当前状态 
  705. ********************************************************/  
  706. void grid::DisplayGrid()  
  707. {  
  708.     int Left,Right,button,top;  
  709.     Left=0,Right=winWidth,button=0,top=winHeight;  
  710.     int lx1,ly1,lx2,ly2;  
  711.     glClear(GL_COLOR_BUFFER_BIT);  
  712.     glColor3f(0.0f,0.0f,1.0f);  
  713.     glPointSize(5);  
  714.   
  715.     //绘制放个水平线  
  716.     for(int i=0;i<=winWidth;i+=this->ColumnInc)  
  717.     {  
  718.         DDALine(Left+i,button,Left+i,top);  
  719.     }  
  720.   
  721.     //绘制放个竖直线线  
  722.     for(int i=0;i<=winHeight;i+=this->RowInc)  
  723.     {  
  724.         DDALine(Left,button+i,Right,button+i);  
  725.     }  
  726.   
  727.     //绘制障碍物  
  728.     for(int i=0;i<this->UsedPointNumber;i++)  
  729.     {  
  730.         glColor3f(1.0f,0.0f,0.0f);  
  731.   
  732.         glRectf(Left+this->Point[i].y*this->ColumnInc,button+this->Point[i].x*this->RowInc,  
  733.             Left+this->Point[i].y*this->ColumnInc+this->ColumnInc,button+this->Point[i].x*this->RowInc+this->RowInc);  
  734.     }  
  735.   
  736.     int inc=3;  
  737.     glColor3f(0.0f,1.0f,0.0f);  
  738.     glRectf(Left+Start.y*this->ColumnInc+inc,button+Start.x*this->RowInc+inc,  
  739.         Left+Start.y*this->ColumnInc+this->ColumnInc-inc,button+Start.x*this->RowInc+this->RowInc-inc);  
  740.     //cout<<"S.x="<<Start.x<<"  S.y="<<Start.y<<endl;///  
  741.   
  742.   
  743.     glColor3f(0.0f,.0f,1.0f);  
  744.     glRectf(Left+Target.y*this->ColumnInc+inc,button+Target.x*this->RowInc+inc,  
  745.         Left+Target.y*this->ColumnInc+this->ColumnInc-inc,button+Target.x*this->RowInc+this->RowInc-inc);  
  746.     //cout<<"T.x="<<Target.x<<"  T.y="<<Target.y<<endl;///  
  747.   
  748.     if(!First)//不是第一次初始化窗口,则会出现相应染色体对应的路径  
  749.     {  
  750.         for(int j=this->tcnt;j<this->UsedPointNumber;j++)  
  751.         {  
  752.             glColor3f(0.0f,1.0f,0.0f);  
  753.             glRectf(Left+this->Point[j].y*this->ColumnInc,button+this->Point[j].x*this->RowInc,  
  754.                 Left+this->Point[j].y*this->ColumnInc+this->ColumnInc,button+this->Point[j].x*this->RowInc+this->RowInc);  
  755.         }  
  756.     }  
  757.     glFlush();  
  758. }  
  759.   
  760. /******************************************************* 
  761. *函数名init 
  762. *无参数 
  763. *初始化函数 
  764. ********************************************************/  
  765. void init()  
  766. {  
  767.     glClearColor(0.0f,0.0f,0.0f,1.0f);  
  768.     glMatrixMode(GL_PROJECTION);    //设置投影参数  
  769.     gluOrtho2D(0.0f, 1000.0f,0.0f,600.0f);  
  770.     MyLoop=false;  
  771.     SetRow=false;SetColumn=false;  
  772.     IsRun=false;  
  773.     First=true;  
  774. }  
  775.   
  776. /******************************************************* 
  777. *函数名Display() 
  778. *无参数 
  779. *窗口创建时显示背景色 
  780. ********************************************************/  
  781. void Display()  
  782. {  
  783.     glClear(GL_COLOR_BUFFER_BIT);  
  784.     glFlush();  
  785. }  
  786.   
  787. /******************************************************* 
  788. *函数名ChangeSize 
  789. *无参数 
  790. *窗口发生变化时完成初始化 
  791. ********************************************************/  
  792. void ChangeSize(int w, int h)  
  793. {     
  794.     winWidth=w;winHeight=h;  
  795.     glViewport(0, 0, w, h);                
  796.     glMatrixMode(GL_PROJECTION);        
  797.     glLoadIdentity();             
  798.     gluOrtho2D(0.0,winWidth,0.0,winHeight);  
  799. }  
  800.   
  801.   
  802. /******************************************************* 
  803. *函数名timer 
  804. *无关参数 
  805. *定期刷新窗口 
  806. ********************************************************/  
  807. void Timer(int p)  
  808. {  
  809.     Grid.now_Gen++;  
  810.     if(Grid.now_Gen>=Grid.GenerationNum*Grid.PopulationSize)  
  811.     {  
  812.         Grid.OptimalFitness=Grid.GetFitness(Grid.OptimalPath);  
  813.         Grid.DisplayGrid();  
  814.         return ;  
  815.     }  
  816.     int i=Grid.now_Gen%Grid.PopulationSize;  
  817.     Grid.tcnt=Grid.UsedPointNumber;  
  818.     Grid.Fitness[i]=Grid.GetFitness(Grid.Chro[i]);  
  819.     Grid.DisplayGrid();  
  820.     Grid.UsedPointNumber=Grid.tcnt;  
  821.     if(Grid.now_Gen%Grid.PopulationSize==0)  
  822.     {  
  823.         cout<<Grid.OptimalPath<<endl;  
  824.         cout<<"当前已是第"<<Grid.now_Gen/Grid.PopulationSize<<"代种群!"<<endl;  
  825.         Grid.Selection();  
  826.         Grid.MutationNum=Grid.PopulationSize*Grid.MutationRate;//计算变异个数  
  827.         Grid.CrossoverNum=Grid.PopulationSize*Grid.CrossoverRate/2;//计算交叉个数  
  828.         Grid.Crossover();  
  829.         Grid.Mutation();  
  830.         if(Grid.PopulationSize>10)//精英主义(Elitist Strategy)选择///////////  
  831.         {  
  832.             srand((unsigned)clock());  
  833.             int Index;  
  834.             for(int i=0;i<10;i++)  
  835.             {  
  836.                 Index=rand()%Grid.PopulationSize;  
  837.                 Grid.Chro[Index]=Grid.OptimalPath;  
  838.             }  
  839.         }  
  840.     }  
  841.     if(MyLoop)  
  842.         glutTimerFunc(200,Timer,0);  
  843. }  
  844.   
  845. /******************************************************* 
  846. *函数名MousePlot 
  847. *4个参数:按键类型、动作、对应的坐标 
  848. *鼠标响应函数 
  849. ********************************************************/  
  850. void MousePlot(int button,int action,int x,int y)  
  851. {  
  852.     if(SetRow&&SetColumn)  
  853.     {  
  854.         if(button==GLUT_LEFT_BUTTON&&action==GLUT_DOWN)   
  855.         {     
  856.             if(!MyLoop&&!IsRun)  
  857.             {  
  858.                 memset(Grid.BetDis,0,sizeof(Grid.BetDis));  
  859.                 Grid.InitGrid();  
  860.             }  
  861.             else MyLoop=false;  
  862.         }  
  863.         else if(button==GLUT_MIDDLE_BUTTON&&action==GLUT_DOWN)  
  864.         {  
  865.             MyLoop=true;  
  866.             IsRun=true;  
  867.             First=false;  
  868.             Grid.now_Gen=0;  
  869.             cout<<"当前已是第"<<Grid.now_Gen/Grid.PopulationSize<<"代种群!"<<endl;  
  870.             Grid.MutationNum=0;//交叉个数为0  
  871.             Grid.CrossoverNum=0;//变异个数为0  
  872.             if(Grid.PopulationSize>10)//精英主义(Elitist Strategy)选择///////////  
  873.             {  
  874.             srand((unsigned)clock());  
  875.             int Index;  
  876.             for(int i=0;i<10;i++)  
  877.             {  
  878.                 Index=rand()%Grid.PopulationSize;  
  879.                 Grid.Chro[Index]=Grid.OptimalPath;  
  880.             }  
  881.         }  
  882.             glutTimerFunc(200,Timer,0);  
  883.         }  
  884.     }  
  885. }  
  886.   
  887. /******************************************************* 
  888. *函数名ProcessMenu 
  889. *一个参数,菜单选项 
  890. *菜单响应函数 
  891. ********************************************************/  
  892. void ProcessMenu(int value)  
  893. {  
  894.     if(IsRun)//在运行过程中重置方格  
  895.     {  
  896.         SetRow=false;  
  897.         SetColumn=false;  
  898.         IsRun=false;  
  899.         First=true;  
  900.         MyLoop=false;  
  901.     }  
  902.     if(value<=10)  
  903.     {  
  904.         Grid.SetRow(GridLen[0][value-1]);  
  905.         SetRow=true;  
  906.     }  
  907.     else if(value<=20)  
  908.     {  
  909.         Grid.SetColumn(GridLen[1][value-11]);  
  910.         SetColumn=true;  
  911.     }  
  912. }  
  913.   
  914. /******************************************************* 
  915. *函数名MyCreateMenu 
  916. *无菜单 
  917. *初始化菜单 
  918. ********************************************************/  
  919. void MyCreateMenu()  
  920. {  
  921.     int SetWidth=glutCreateMenu(ProcessMenu);  
  922.     glutAddMenuEntry("4",1);  
  923.     glutAddMenuEntry("6",2);  
  924.     glutAddMenuEntry("8",3);  
  925.     glutAddMenuEntry("10",4);  
  926.     glutAddMenuEntry("12",5);  
  927.     glutAddMenuEntry("14",6);  
  928.     glutAddMenuEntry("16",7);  
  929.     glutAddMenuEntry("18",8);  
  930.     glutAddMenuEntry("20",9);  
  931.     glutAddMenuEntry("22",10);  
  932.     int SetHeight=glutCreateMenu(ProcessMenu);  
  933.     glutAddMenuEntry("4",11);  
  934.     glutAddMenuEntry("6",12);  
  935.     glutAddMenuEntry("8",13);  
  936.     glutAddMenuEntry("10",14);  
  937.     glutAddMenuEntry("12",15);  
  938.     glutAddMenuEntry("14",16);  
  939.     glutAddMenuEntry("16",17);  
  940.     glutAddMenuEntry("18",18);  
  941.     glutAddMenuEntry("20",19);  
  942.     glutAddMenuEntry("22",20);  
  943.     int Choice=glutCreateMenu(ProcessMenu);  
  944.     glutAddSubMenu("水平方向方格数",SetWidth);  
  945.     glutAddSubMenu("垂直方向方格数",SetHeight);  
  946.     glutCreateMenu(ProcessMenu);  
  947.     glutAddSubMenu("设置",Choice);  
  948.     glutAttachMenu(GLUT_RIGHT_BUTTON);  
  949. }  
  950.   
  951.   
  952. int main(int argc, char *argv[])  
  953. {     
  954.     InitMap();  
  955.     glutInit(&argc,argv);  
  956.     glutInitDisplayMode(GLUT_RGB|GLUT_SINGLE);  
  957.     glutInitWindowPosition(0, 0);  
  958.     glutInitWindowSize(1000, 600);  
  959.     glutCreateWindow("遗传算法在方格中的求最短路径动画演示");  
  960.     glutDisplayFunc(Display);  
  961.     glutReshapeFunc(ChangeSize);  
  962.     glutMouseFunc(MousePlot);  
  963.     MyCreateMenu();  
  964.     init();  
  965.     glutMainLoop();       
  966.     return 0;  
  967. }  



不用BFS算发引导

  1. #include<windows.h>  
  2. #include<gl/glut.h>   
  3. #include<iostream>  
  4. #include<string>  
  5. #include<vector>  
  6. #include<cstdio>  
  7. #include<cstring>  
  8. #include<cmath>  
  9. #include<cstdlib>  
  10. #include<ctime>  
  11. #include<iomanip>  
  12. #include<map>  
  13. #include<algorithm>  
  14. #include<queue>  
  15. using namespace std;  
  16.   
  17. const int MAXNGRID=1000;//设置方格的总数  
  18. const int MAXROC=50;//设置最大长、宽  
  19. const int MAXCHRO=250;//染色体条数  
  20. const double eps=1e-10;  
  21.   
  22. int winHeight,winWidth;//当前窗口的长宽  
  23. bool MyLoop,SetRow,SetColumn,IsRun,First;//几个开关变量控制鼠标响应  
  24. int GridLen[2][10]=  
  25. {  
  26.     {4,6,8,10,12,14,16,18,20,22},  
  27.     {4,6,8,10,12,14,16,18,20,22}  
  28. };  
  29. int Move[4][2]={{-1,0},{1,0},{0,-1},{0,1}};  
  30.   
  31. struct state   
  32. {  
  33.     int x,y;  
  34.     int dis;  
  35.     string path;  
  36. }Start,Target;  
  37. queue<state>Qu;  
  38.   
  39. struct point  
  40. {  
  41.     int x,y;  
  42. };//建立方格的坐标(规则同OpenGL),便于投影到视区  
  43.   
  44. map<int,string>Mat;  
  45.   
  46. void InitMap()  
  47. {  
  48.     Mat[0]="00";Mat[1]="01";Mat[2]="10";Mat[3]="11";  
  49. }  
  50.   
  51. class grid  
  52. {  
  53. private :  
  54.     int Row,Column; //方格的行列  
  55.     int TotalPointNumber,UsedPointNumber;      //总的点数、已用点数  
  56.     int GenerationNum,PopulationSize,MaxDis,MinDis;//繁殖代数、种群规模、最大距离、最短距离  
  57.     int BetDis[MAXROC][MAXROC];//BetDis[x][y]表示(x,y)到目标点的最短距离  
  58.     int tcnt;           //全局临时变量  
  59.     string OptimalPath;//遗传算法求得的最短路径  
  60.     string BFSPath;    //BFS算法最短路径  
  61.     double OptimalFitness;//已找到的最短路径  
  62.     point Point[MAXNGRID];  //待打印的点  
  63.     double RowInc,ColumnInc; //窗口的行列步长  
  64.     bool Mark[MAXROC][MAXROC];//标记有没有访问  
  65.     double MutationRate;      //变异率  
  66.     double CrossoverRate;     //杂交率  
  67.     double MutationNum;       //当代变异个数  
  68.     double CrossoverNum;       //当代交叉个数  
  69.     int now_Gen;              //当前代数  
  70.     double Fitness[MAXCHRO];   //适应度  
  71.     double Random[MAXCHRO];    //产生的随机数  
  72.     double ProSec[MAXCHRO];    //选择概率  
  73.     double ProAccu[MAXCHRO];  //累积选择概率  
  74.     vector<string>Chro;      //染色体  
  75.     bool IsUsed[MAXCHRO];//标记当前繁殖代数下该染色体是否已经交叉或变异过  
  76. public:  
  77.     int GetRow();  
  78.     int GetColumn();  
  79.     void SetRow(int);  
  80.     void SetColumn(int);  
  81.     bool BFS();  
  82.     void DisplayGrid();  
  83.     void InitGrid();  
  84.     void DDALine(int,int,int,int);  
  85.     void GetMinMaxDis();  
  86.     bool IsBump(int,int);  
  87.     bool GetNext(int &,int &,int);  
  88.     int RunRoute(int &,int &,string &);  
  89.     double GetFitness(string &);  
  90.     void Manu_Init();  
  91.     int GetRand(int);  
  92.     void Mutation();  
  93.     void My_Rand();  
  94.     void Get_Sec_num();  
  95.     void Selection();  
  96.     void GetCros(int,int,int,int);  
  97.     void Crossover();  
  98.     friend void Timer(int);  
  99.     friend void MousePlot(int,int,int,int);  
  100. }Grid;  
  101.   
  102. /************************************************ 
  103. *函数名GetRow 
  104. *无参数 
  105. *获得方格行数 
  106. *************************************************/  
  107. int grid::GetRow()  
  108. {  
  109.     return this->Row;  
  110. }  
  111.   
  112. /************************************************ 
  113. *函数名GetColumn 
  114. *无参数 
  115. *获得方格列数 
  116. *************************************************/  
  117. int grid::GetColumn()  
  118. {  
  119.     return this->Column;  
  120. }  
  121.   
  122. /************************************************ 
  123. *函数名SetRow 
  124. *无参数 
  125. *设置方格行数 
  126. *************************************************/  
  127. void grid::SetRow(int row)  
  128. {  
  129.     this->Row=row;  
  130. }  
  131.   
  132. /************************************************ 
  133. *函数名SetColumn 
  134. *无参数 
  135. *设置方格列数 
  136. *************************************************/  
  137. void grid::SetColumn(int column)  
  138. {  
  139.     this->Column=column;  
  140. }  
  141.   
  142. /****************************************************************************** 
  143. *函数名GetMinMaxDis 
  144. *无参数          
  145. *计算路径可能的最小距离和最大距离 
  146. *******************************************************************************/  
  147. void grid::GetMinMaxDis()  
  148. {  
  149.     this->MaxDis=(this->Row)*(this->Column);  
  150.     this->MinDis=abs(Target.x-Start.x)+abs(Target.y-Start.y);  
  151. }  
  152.   
  153. /****************************************************************************** 
  154. *函数名IsBump 
  155. *两个参数分别表示横坐标、纵坐标          
  156. *判断当前是否合法,及是否撞墙或越界 
  157. *******************************************************************************/  
  158. bool grid::IsBump(int tRow,int tColumn)  
  159. {  
  160.     if(tRow<0||tRow>=this->Row||tColumn<0||tColumn>=this->Column||this->Mark[tRow][tColumn])  
  161.         return true;  
  162.     return false;  
  163. }  
  164.   
  165. /****************************************************************************** 
  166. *函数名GetNext 
  167. *当前的坐标,移动方向        
  168. *若下一个是合法状态,移到该状态,返回true;否则不做操作返回false 
  169. *******************************************************************************/  
  170. bool grid::GetNext(int &tRow,int &tColumn,int tDirection)  
  171. {  
  172.     int incx,incy;  
  173.     if(0==tDirection)          incx=-1,incy= 0;  
  174.     else if(1==tDirection)     incx= 0,incy= 1;  
  175.     else if(2==tDirection)     incx= 1,incy= 0;  
  176.     else                       incx= 0,incy=-1;  
  177.     if(!(this->IsBump(tRow+incx,tColumn+incy)))  
  178.     {  
  179.         tRow=tRow+incx,tColumn=tColumn+incy;  
  180.         return true;//当前方向有效  
  181.     }  
  182.     return false;//当前方向无效  
  183. }  
  184.   
  185.   
  186. /****************************************************************************** 
  187. *函数名:RunRoute 
  188. *3个参数分别表示当前点的坐标,和当前处理染色体的引用         
  189. * 寻找并记录染色体对应的有效路径同时修改不合法的染色体 
  190. *******************************************************************************/  
  191. int grid::RunRoute(int &tRow,int &tColumn,string &Chromosome)  
  192. {  
  193.     int size=Chromosome.size();  
  194.     int Direction;  
  195.     int len=1;  
  196.     string newchro;  
  197.     string tmp;  
  198.     for(int i=0;i<size;i+=2)  
  199.     {  
  200.         tmp.clear();  
  201.         tmp+=Chromosome[i];  
  202.         tmp+=Chromosome[i+1];  
  203.         if(tmp=="00")  
  204.         {  
  205.             Direction=0;  
  206.         }  
  207.         else if(tmp=="01")  
  208.         {  
  209.             Direction=1;  
  210.         }  
  211.         else if(tmp=="10")  
  212.         {  
  213.             Direction=2;  
  214.         }  
  215.         else  
  216.         {  
  217.             Direction=3;  
  218.         }  
  219.         int tR=tRow,tC=tColumn;  
  220.         while(!this->GetNext(tRow,tColumn,Direction))  
  221.             //当前方向不合法,则转到下一方向;如果除去来的其他3个方向都不合法,则返回当前位置的前一个位置  
  222.                 //此处最好的方法是回溯法,类比深搜,但时间复杂度是不能接受的,最坏可达O(4^n)  
  223.         {  
  224.             Direction=(Direction+1)%4;  
  225.             tmp=Mat[Direction];  
  226.         }  
  227.         Chromosome[i]=tmp[0];//修正染色体  
  228.         Chromosome[i+1]=tmp[1];  
  229.         newchro+=tmp;  
  230.         if(tRow==Target.x&&tColumn==Target.y)  
  231.         {  
  232.             Chromosome=newchro;//找到目标点也做修改染色体,保证路径尽可能短  
  233.             return len;  
  234.         }  
  235.         this->Point[this->UsedPointNumber].x=tRow;  
  236.         this->Point[this->UsedPointNumber].y=tColumn;  
  237.         this->UsedPointNumber++;  
  238.         len++;  
  239.     }  
  240.     return len;  
  241. }  
  242.   
  243. /****************************************************************************** 
  244. *函数名GetFitness 
  245. *一个参数为当前处理染色体的引用         
  246. *计算个体适应度 
  247. *******************************************************************************/  
  248. double grid::GetFitness(string &Chromosome)  
  249. {  
  250.     int Row=Start.x,Column=Start.y;  
  251.     int len=this->RunRoute(Row,Column,Chromosome);  
  252.     if(Row==Target.x&&Column==Target.y)  
  253.     {  
  254.         return 1.0;  
  255.     }  
  256.     //double tmpdis=abs(Target.x-Row)+abs(Target.y-Column);  
  257.     double tmpdis=this->BetDis[Row][Column];//此时tmpdis表示到目标点的最短路径长  
  258.     double ret=1-tmpdis/(this->MaxDis);  
  259.     //double ret=1.0*(1-tmpdis/MaxDis)+1.0/len;//保证len不为0  
  260.     return ret;  
  261. }  
  262.   
  263. /****************************************************************************** 
  264. *函数名ChromosomeCmp 
  265. *两个参数,分别表示两条染色体       
  266. *依据长度从小到大对染色体进行排序,方便交叉 
  267. *******************************************************************************/  
  268. bool ChromosomeCmp(string tmpa,string tmpb)  
  269. {  
  270.     return tmpa.size()<tmpb.size();  
  271. }  
  272.   
  273. /****************************************************************************** 
  274. *函数名Manu_Init 
  275. *无参数           
  276. *随机初始化种群 
  277. 难点在于染色体长度和表征的路径的控制,在此我没有找到对应随机游戏局面的比较好的初始化方案 
  278. 原因在于局面是随机任意的,且找路径的个体是看不知全局的,只能随便跑,我认为人为干预是不恰当的 
  279. *******************************************************************************/  
  280. void grid::Manu_Init()  
  281. {  
  282.     this->Chro.clear();  
  283.     this->GetMinMaxDis();         //获得最大值、最小值  
  284.     int minlen=this->MinDis;  
  285.     int maxlen=((this->MaxDis)-(this->UsedPointNumber))/3;  
  286.     this->PopulationSize=200;///  
  287.     this->GenerationNum=1000;  
  288.     srand((unsigned)clock());  
  289.     string tmp;  
  290.     for(int i=0;i<this->PopulationSize;i++)  
  291.     {  
  292.         tmp.clear();  
  293.         int len;  
  294.         do  
  295.         {  
  296.             len=rand()%maxlen;  
  297.             if(len%2)len++;//保证染色体长度为偶数  
  298.         }while(len<minlen);//控制染色体长度在[minlen,maxlen)之间  
  299.         while(len)  
  300.         {  
  301.             int id=rand()%4;  
  302.             tmp+=Mat[id];  
  303.             len--;  
  304.         }  
  305.         (this->Chro).push_back(tmp);  
  306.     }  
  307.     this->OptimalPath=this->Chro[0];  
  308.     this->OptimalFitness=0;  
  309.     this->CrossoverRate=0.5;  
  310.     this->MutationRate=0.05;  
  311. }  
  312.   
  313. /****************************************************************************** 
  314. *函数名GetRand 
  315. *一个参数,表示上限          
  316. *返回【0,len)的随机数 
  317. *******************************************************************************/  
  318. int grid::GetRand(int len)  
  319. {  
  320.     double be=1.0/(len);  
  321.     double Rand=1.0*rand()/(RAND_MAX);  
  322.     int ret=(int)(Rand/be);  
  323.     if(ret>=len)ret--;  
  324.     return ret;  
  325. }  
  326.   
  327. /****************************************************************************** 
  328. *函数名Mutation() 
  329. * 无参数         
  330. *随机选染色体,再随机选一个基因片段变异,变异方向不确定 
  331. *******************************************************************************/  
  332. void grid::Mutation()  
  333. {  
  334.     int belong,id,to,size=this->Chro.size();  
  335.     string tmp;  
  336.     srand((unsigned)clock());  
  337.     memset(this->IsUsed,0,sizeof(this->IsUsed));  
  338.     while(this->MutationNum>1)  
  339.     {  
  340.         do  
  341.         {  
  342.             do  
  343.             {  
  344.                 belong=this->GetRand(size);//属于哪个染色体  
  345.             }while(this->IsUsed[belong]);//选择当前代没变异过的  
  346.             id=this->GetRand(this->Chro[belong].size()/2);//变异那个片段  
  347.             to=GetRand(4);  
  348.             tmp.clear();  
  349.             tmp=this->Chro[belong];  
  350.             tmp[id*2]=Mat[to][0];  
  351.             tmp[id*2+1]=Mat[to][1];  
  352.         }while(tmp==this->Chro[belong]);//保证变异后与原来不同  
  353.         this->Chro[belong]=tmp;  
  354.         this->MutationNum-=1;  
  355.     }  
  356. }  
  357.   
  358. /****************************************************************************** 
  359. *函数名My_Rand 
  360. *无参数          
  361. *产生一组[0,1]内的分布均匀的随机数 
  362. *******************************************************************************/  
  363. void grid::My_Rand()  
  364. {  
  365.     srand((unsigned)clock());  
  366.     int size=this->Chro.size();  
  367.     for(int i=0;i<size;i++)  
  368.     {  
  369.         this->Random[i]=1.0*rand()/RAND_MAX;  
  370.     }  
  371. }  
  372.   
  373.   
  374. /****************************************************************************** 
  375. *函数名Get_Sec_num 
  376. *无参数          
  377. *利用赌轮选择法选择适应度大的生存下来 
  378. *******************************************************************************/  
  379. void grid::Get_Sec_num()  
  380. {  
  381.     this->My_Rand();  
  382.     vector<string>TmpChromosome;  
  383.     int j=0;  
  384.     int size=this->Chro.size();  
  385.     while(j<size)  
  386.     {  
  387.         int i;  
  388.         for(i=1;i<=size;i++)  
  389.         {  
  390.             if(this->Random[j]<=this->ProAccu[i]+eps)//防止浮点数误差  
  391.             {  
  392.                 TmpChromosome.push_back(this->Chro[i-1]);  
  393.                 j++;  
  394.                 break;  
  395.             }  
  396.         }  
  397.     }  
  398.     for(int i=0;i<size;i++)  
  399.         this->Chro[i]=TmpChromosome[i];  
  400.     TmpChromosome.clear();  
  401. }  
  402.   
  403. /****************************************************************************** 
  404. *函数名 
  405. *无参数         
  406. *遗传操作-选择主函数 
  407. *******************************************************************************/  
  408. void grid::Selection()  
  409. {  
  410.     int size=this->Chro.size();  
  411.     double sum=0;  
  412.     this->OptimalFitness=0;  
  413.     this->OptimalPath.clear();  
  414.     for(int i=0;i<size;i++)  
  415.     {  
  416.         sum+=this->Fitness[i];  
  417.         if(this->Fitness[i]>this->OptimalFitness||((fabs(this->Fitness[i]-this->OptimalFitness)<=eps)&&this->OptimalPath.size()>this->Chro[i].size()))  
  418.         {  
  419.             this->OptimalFitness=this->Fitness[i];  
  420.             this->OptimalPath=this->Chro[i];  
  421.         }  
  422.     }  
  423.     for(int i=1;i<=size;i++)  
  424.     {  
  425.         this->ProSec[i]=this->Fitness[i-1]/sum;  
  426.     }  
  427.     this->ProAccu[0]=0;  
  428.     for(int i=1;i<=size;i++)  
  429.         this->ProAccu[i]=this->ProAccu[i-1]+this->ProSec[i];  
  430.     this->Get_Sec_num();  
  431. }  
  432.   
  433. /****************************************************************************** 
  434. *函数名GetCros 
  435. *4个参数,分别表示带交叉的两条染色体的下标,以及对应的交叉位置    
  436. *功能遗传操作-交叉函数 
  437. *******************************************************************************/  
  438. void grid::GetCros(int One,int Two,int From,int To)  
  439. {  
  440.     string tmp;  
  441.     for(int i=From;i<=To;i++)  
  442.     {  
  443.         tmp.clear();  
  444.         tmp+=this->Chro[One][i*2];  
  445.         tmp+=this->Chro[One][i*2+1];  
  446.         this->Chro[One][i*2]=this->Chro[Two][i*2];  
  447.         this->Chro[One][i*2+1]=this->Chro[Two][i*2+1];  
  448.         this->Chro[Two][i*2]=tmp[0];  
  449.         this->Chro[Two][i*2+1]=tmp[1];  
  450.     }  
  451. }  
  452.   
  453. /****************************************************************************** 
  454. *函数名Crossover 
  455. *无参数  
  456. *功能遗传操作-交叉主函数,选择相同长度的染色体进行交叉 
  457. *******************************************************************************/  
  458. void grid::Crossover()  
  459. {  
  460.     sort(this->Chro.begin(),this->Chro.end(),ChromosomeCmp);  
  461.     int id,id1,id2,size=this->Chro.size();  
  462.     bool flag;  
  463.     memset(this->IsUsed,0,sizeof(this->IsUsed));  
  464.     while(this->CrossoverNum>1.0)  
  465.     {  
  466.         flag=false;  
  467.         do  
  468.         {  
  469.             id=this->GetRand(size);  
  470.         }while(this->IsUsed[id]);//选择没交叉过的染色体  
  471.         int tsize=(this->Chro[id]).size();  
  472.   
  473.         ///////选择长度相同且没交叉过的染色体  
  474.         if(id!=0&&!(this->IsUsed[id-1])&&tsize==this->Chro[id-1].size())  
  475.         {  
  476.             flag=true;  
  477.             do  
  478.             {  
  479.                 id1=this->GetRand(tsize/2);  
  480.                 id2=this->GetRand(tsize/2);  
  481.             }while(id1>id2);  
  482.             this->GetCros(id,id-1,id1,id2);  
  483.         }  
  484.         if(!flag&&id!=size-1&&!(this->IsUsed[id+1])&&tsize==this->Chro[id+1].size())  
  485.         {  
  486.             flag=true;  
  487.             do  
  488.             {  
  489.                 id1=this->GetRand(tsize/2);  
  490.                 id2=this->GetRand(tsize/2);  
  491.             }while(id1>id2);  
  492.             this->GetCros(id,id+1,id1,id2);  
  493.         }  
  494.         if(flag)this->CrossoverNum-=1;  
  495.     }  
  496. }  
  497.   
  498. /************************************************ 
  499. *函数名BFS 
  500. *无参数 
  501. *利用广度优先预处理所有的点到目标点的最近距离 
  502. *************************************************/  
  503. bool grid::BFS()  
  504. {  
  505.     state Now,Next;  
  506.     while(!Qu.empty())  
  507.         Qu.pop();  
  508.     Qu.push(Target);  
  509.     Target.dis=0;  
  510.     Target.path.clear();  
  511.     this->BFSPath.clear();  
  512.     bool Visited[MAXROC][MAXROC];  
  513.     memcpy(Visited,Mark,sizeof(Mark));  
  514.     Visited[Target.x][Target.y]=true;  
  515.     while(!Qu.empty())  
  516.     {  
  517.         Now=Qu.front();Qu.pop();  
  518.         if(Now.x==Target.x&&Now.y==Target.y)  
  519.         {  
  520.             this->BFSPath=Now.path;          //此处记录广度优先的最短路径  
  521.         }  
  522.         for(int i=0;i<4;i++)  
  523.         {  
  524.             int tx=Now.x+Move[i][0];   
  525.             int ty=Now.y+Move[i][1];  
  526.             int dis=Now.dis+1;  
  527.             if(!(tx<0||tx>=this->Row||ty<0||ty>=this->Column||Visited[tx][ty]))  
  528.             {  
  529.                 Next.x=tx;  
  530.                 Next.y=ty;  
  531.                 Next.dis=dis;  
  532.                 this->BetDis[tx][ty]=dis;  
  533.                 Visited[tx][ty]=true;  
  534.                 Next.path=Now.path;  
  535.                 if(0==i)Next.path+='U';  
  536.                 else if(1==i)Next.path+='D';  
  537.                 else if(2==i)Next.path+='L';  
  538.                 else if(3==i)Next.path+='R';  
  539.                 Qu.push(Next);  
  540.             }  
  541.         }  
  542.     }  
  543.     return false;  
  544. }  
  545.   
  546. /******************************************************* 
  547. *函数名DDALine 
  548. *无参数 
  549. *利用数值微分法由确定的两个端点画直线 
  550. ********************************************************/  
  551. void grid::DDALine(int lx1,int ly1,int lx2,int ly2)  
  552. {  
  553.     int dx,dy,epsl,k;  
  554.     float x,y,xIncre,yIncre;  
  555.     dx=lx2-lx1;   dy=ly2-ly1;  
  556.     x=lx1;        y=ly1;  
  557.     if(abs(dx)>abs(dy))  
  558.         epsl=abs(dx);  
  559.     else epsl=abs(dy);  
  560.     xIncre=(float)dx/(float)epsl;  
  561.     yIncre=(float)dy/(float)epsl;  
  562.     glBegin(GL_POINTS);//  
  563.     for(k=0;k<=epsl;k++)  
  564.     {  
  565.         glVertex2i(int(x+0.5),int(y+0.5));     
  566.         x+=xIncre;  
  567.         y+=yIncre;  
  568.     }  
  569.     glEnd();   
  570. }        
  571.   
  572. /******************************************************* 
  573. *函数名InitGrid 
  574. *无参数 
  575. *显示每局的障碍、起点、目标点 
  576. ********************************************************/  
  577. void grid::InitGrid()  
  578. {  
  579.     this->UsedPointNumber=0;  
  580.     this->TotalPointNumber=this->Row*this->Column;  
  581.     this->RowInc=winHeight/this->Row,this->ColumnInc=winWidth/this->Column;  
  582.     memset(this->Mark,false,sizeof(this->Mark));  
  583.     srand((unsigned)clock());  
  584.     do  
  585.     {  
  586.         this->UsedPointNumber=rand()%(this->TotalPointNumber);  
  587.     }while(this->UsedPointNumber>=this->TotalPointNumber/4||this->UsedPointNumber<=this->TotalPointNumber/8);  
  588.     //尽可能合理的控制障碍的数目  
  589.     int tmp=0;  
  590.     while(tmp<this->UsedPointNumber)//产生障碍的坐标并尽可能保证适当数目的障碍连成一串  
  591.     {  
  592.         int x=rand()%(this->Row),y=rand()%(this->Column),bel=rand()%2;  
  593.         if(0==bel)//(x-1,y),(x,y),(x+1,y)  
  594.         {  
  595.             if(x-1>=0)  
  596.             {  
  597.                 this->Point[tmp].y=y;this->Point[tmp].x=x-1;tmp++;  
  598.                 this->Mark[x-1][y]=true;  
  599.                 if(tmp>=this->UsedPointNumber)break;  
  600.             }  
  601.             if(x<this->Row)  
  602.             {  
  603.                 this->Point[tmp].y=y;this->Point[tmp].x=x;tmp++;  
  604.                 this->Mark[x][y]=true;  
  605.                 if(tmp>=this->UsedPointNumber)break;  
  606.             }  
  607.             if(x+1<this->Row)  
  608.             {  
  609.                 this->Point[tmp].y=y;this->Point[tmp].x=x+1;tmp++;  
  610.                 this->Mark[x+1][y]=true;  
  611.                 if(tmp>=this->UsedPointNumber)break;  
  612.             }  
  613.         }  
  614.         else //(x,y-1),(x,y),(x,y+1)  
  615.         {  
  616.             if(y-1>=0)  
  617.             {  
  618.                 this->Point[tmp].y=y-1;this->Point[tmp].x=x;tmp++;  
  619.                 this->Mark[x][y-1]=true;  
  620.                 if(tmp>=this->UsedPointNumber)break;  
  621.             }  
  622.             if(y<this->Column)  
  623.             {  
  624.                 this->Point[tmp].y=y;this->Point[tmp].x=x;tmp++;  
  625.                 this->Mark[x][y]=true;  
  626.                 if(tmp>=this->UsedPointNumber)break;  
  627.             }  
  628.             if(y+1<this->Column)  
  629.             {  
  630.                 this->Point[tmp].y=y+1;this->Point[tmp].x=x;tmp++;  
  631.                 this->Mark[x][y+1]=true;  
  632.                 if(tmp>=this->UsedPointNumber)break;  
  633.             }  
  634.         }  
  635.     }  
  636.     int sx,sy,tx,ty;  
  637.     do  
  638.     {  
  639.         do  
  640.         {  
  641.             sx=rand()%(this->Row);  
  642.             sy=rand()%(this->Column);  
  643.         }while(this->Mark[sx][sy]);//控制起点无障碍物  
  644.         do  
  645.         {  
  646.             tx=rand()%(this->Row);  
  647.             ty=rand()%(this->Column);  
  648.         }while(this->Mark[tx][ty]);//控制目标点无障碍物  
  649.     }while(abs(sx-tx)+abs(sy-ty)<(this->Row+this->Column)/3);//控制起点和目标点保持适当远的距离不小于方格任意两点最大哈夫曼距离的三分之一  
  650.     this->Mark[sx][sy]=true;  
  651.     Start.x=sx;Start.y=sy;  
  652.     this->Mark[tx][ty]=true;  
  653.     Target.x=tx;Target.y=ty;  
  654.     this->Manu_Init();  
  655.     this->DisplayGrid();  
  656.     this->BFS();  
  657.     if(IsRun)First=false;  
  658.     if(IsRun)First=false;  
  659. }  
  660.   
  661. /******************************************************* 
  662. *函数名DisplayGrid 
  663. *无参数 
  664. *显示窗口的当前状态 
  665. ********************************************************/  
  666. void grid::DisplayGrid()  
  667. {  
  668.     int Left,Right,button,top;  
  669.     Left=0,Right=winWidth,button=0,top=winHeight;  
  670.     int lx1,ly1,lx2,ly2;  
  671.     glClear(GL_COLOR_BUFFER_BIT);  
  672.     glColor3f(0.0f,0.0f,1.0f);  
  673.     glPointSize(5);  
  674.   
  675.     //绘制放个水平线  
  676.     for(int i=0;i<=winWidth;i+=this->ColumnInc)  
  677.     {  
  678.         DDALine(Left+i,button,Left+i,top);  
  679.     }  
  680.   
  681.     //绘制放个竖直线线  
  682.     for(int i=0;i<=winHeight;i+=this->RowInc)  
  683.     {  
  684.         DDALine(Left,button+i,Right,button+i);  
  685.     }  
  686.   
  687.     //绘制障碍物  
  688.     for(int i=0;i<this->UsedPointNumber;i++)  
  689.     {  
  690.         glColor3f(1.0f,0.0f,0.0f);  
  691.   
  692.         glRectf(Left+this->Point[i].y*this->ColumnInc,button+this->Point[i].x*this->RowInc,  
  693.             Left+this->Point[i].y*this->ColumnInc+this->ColumnInc,button+this->Point[i].x*this->RowInc+this->RowInc);  
  694.     }  
  695.   
  696.     int inc=3;  
  697.     glColor3f(1.0f,1.0f,0.0f);  
  698.     glRectf(Left+Start.y*this->ColumnInc+inc,button+Start.x*this->RowInc+inc,  
  699.         Left+Start.y*this->ColumnInc+this->ColumnInc-inc,button+Start.x*this->RowInc+this->RowInc-inc);  
  700.   
  701.     glColor3f(1.0f,.0f,1.0f);  
  702.     glRectf(Left+Target.y*this->ColumnInc+inc,button+Target.x*this->RowInc+inc,  
  703.         Left+Target.y*this->ColumnInc+this->ColumnInc-inc,button+Target.x*this->RowInc+this->RowInc-inc);  
  704.   
  705.     if(!First)//不是第一次初始化窗口,则会出现相应染色体对应的路径  
  706.     {  
  707.         for(int j=this->tcnt;j<this->UsedPointNumber;j++)  
  708.         {  
  709.             glColor3f(0.0f,1.0f,0.0f);  
  710.             glRectf(Left+this->Point[j].y*this->ColumnInc,button+this->Point[j].x*this->RowInc,  
  711.                 Left+this->Point[j].y*this->ColumnInc+this->ColumnInc,button+this->Point[j].x*this->RowInc+this->RowInc);  
  712.         }  
  713.     }  
  714.     glFlush();  
  715. }  
  716.   
  717. /******************************************************* 
  718. *函数名init 
  719. *无参数 
  720. *初始化函数 
  721. ********************************************************/  
  722. void init()  
  723. {  
  724.     glClearColor(0.0f,0.0f,0.0f,1.0f);  
  725.     glMatrixMode(GL_PROJECTION);    //设置投影参数  
  726.     gluOrtho2D(0.0f, 1000.0f,0.0f,600.0f);  
  727.     MyLoop=false;  
  728.     SetRow=false;SetColumn=false;  
  729.     IsRun=false;  
  730.     First=true;  
  731. }  
  732.   
  733. /******************************************************* 
  734. *函数名Display() 
  735. *无参数 
  736. *窗口创建时显示背景色 
  737. ********************************************************/  
  738. void Display()  
  739. {  
  740.     glClear(GL_COLOR_BUFFER_BIT);  
  741.     glFlush();  
  742. }  
  743.   
  744. /******************************************************* 
  745. *函数名ChangeSize 
  746. *无参数 
  747. *窗口发生变化时完成初始化 
  748. ********************************************************/  
  749. void ChangeSize(int w, int h)  
  750. {     
  751.     winWidth=w;winHeight=h;  
  752.     glViewport(0, 0, w, h);                
  753.     glMatrixMode(GL_PROJECTION);        
  754.     glLoadIdentity();             
  755.     gluOrtho2D(0.0,winWidth,0.0,winHeight);  
  756. }  
  757.   
  758.   
  759. /******************************************************* 
  760. *函数名timer 
  761. *无关参数 
  762. *定期刷新窗口 
  763. ********************************************************/  
  764. void Timer(int p)  
  765. {  
  766.     Grid.now_Gen++;  
  767.     if(Grid.now_Gen>=Grid.GenerationNum*Grid.PopulationSize)  
  768.     {  
  769.         Grid.OptimalFitness=Grid.GetFitness(Grid.OptimalPath);  
  770.         Grid.DisplayGrid();  
  771.         return ;  
  772.     }  
  773.     int i=Grid.now_Gen%Grid.PopulationSize;  
  774.     Grid.tcnt=Grid.UsedPointNumber;  
  775.     Grid.Fitness[i]=Grid.GetFitness(Grid.Chro[i]);  
  776.     Grid.DisplayGrid();  
  777.     Grid.UsedPointNumber=Grid.tcnt;  
  778.     if(Grid.now_Gen%Grid.PopulationSize==0)  
  779.     {  
  780.         cout<<"当前已是第"<<Grid.now_Gen/Grid.PopulationSize<<"代种群!"<<endl;  
  781.         Grid.Selection();  
  782.         Grid.MutationNum=Grid.PopulationSize*Grid.MutationRate;//计算变异个数  
  783.         Grid.CrossoverNum=Grid.PopulationSize*Grid.CrossoverRate/2;//计算交叉个数  
  784.         Grid.Crossover();  
  785.         Grid.Mutation();  
  786.         if(Grid.PopulationSize>10)//精英主义(Elitist Strategy)选择///////////  
  787.         {  
  788.             srand((unsigned)clock());  
  789.             int Index;  
  790.             for(int i=0;i<10;i++)  
  791.             {  
  792.                 Index=rand()%Grid.PopulationSize;  
  793.                 Grid.Chro[Index]=Grid.OptimalPath;  
  794.             }  
  795.         }  
  796.     }  
  797.     if(MyLoop)  
  798.         glutTimerFunc(200,Timer,0);  
  799. }  
  800.   
  801. /******************************************************* 
  802. *函数名MousePlot 
  803. *4个参数:按键类型、动作、对应的坐标 
  804. *鼠标响应函数 
  805. ********************************************************/  
  806. void MousePlot(int button,int action,int x,int y)  
  807. {  
  808.     if(SetRow&&SetColumn)  
  809.     {  
  810.         if(button==GLUT_LEFT_BUTTON&&action==GLUT_DOWN)   
  811.         {     
  812.             if(!MyLoop&&!IsRun)  
  813.             {  
  814.                 memset(Grid.BetDis,0,sizeof(Grid.BetDis));  
  815.                 Grid.InitGrid();  
  816.             }  
  817.             else MyLoop=false;  
  818.         }  
  819.         else if(button==GLUT_MIDDLE_BUTTON&&action==GLUT_DOWN)  
  820.         {  
  821.             MyLoop=true;  
  822.             IsRun=true;  
  823.             First=false;  
  824.             Grid.now_Gen=0;  
  825.             cout<<"当前已是第"<<Grid.now_Gen/Grid.PopulationSize<<"代种群!"<<endl;  
  826.             Grid.MutationNum=0;//交叉个数为0  
  827.             Grid.CrossoverNum=0;//变异个数为0  
  828.             glutTimerFunc(200,Timer,0);  
  829.         }  
  830.     }  
  831. }  
  832.   
  833. /******************************************************* 
  834. *函数名ProcessMenu 
  835. *一个参数,菜单选项 
  836. *菜单响应函数 
  837. ********************************************************/  
  838. void ProcessMenu(int value)  
  839. {  
  840.     if(IsRun)//在运行过程中重置方格  
  841.     {  
  842.         SetRow=false;  
  843.         SetColumn=false;  
  844.         IsRun=false;  
  845.         First=true;  
  846.         MyLoop=false;  
  847.     }  
  848.     if(value<=10)  
  849.     {  
  850.         Grid.SetRow(GridLen[0][value-1]);  
  851.         SetRow=true;  
  852.     }  
  853.     else if(value<=20)  
  854.     {  
  855.         Grid.SetColumn(GridLen[1][value-11]);  
  856.         SetColumn=true;  
  857.     }  
  858. }  
  859.   
  860. /******************************************************* 
  861. *函数名MyCreateMenu 
  862. *无菜单 
  863. *初始化菜单 
  864. ********************************************************/  
  865. void MyCreateMenu()  
  866. {  
  867.     int SetWidth=glutCreateMenu(ProcessMenu);  
  868.     glutAddMenuEntry("4",1);  
  869.     glutAddMenuEntry("6",2);  
  870.     glutAddMenuEntry("8",3);  
  871.     glutAddMenuEntry("10",4);  
  872.     glutAddMenuEntry("12",5);  
  873.     glutAddMenuEntry("14",6);  
  874.     glutAddMenuEntry("16",7);  
  875.     glutAddMenuEntry("18",8);  
  876.     glutAddMenuEntry("20",9);  
  877.     glutAddMenuEntry("22",10);  
  878.     int SetHeight=glutCreateMenu(ProcessMenu);  
  879.     glutAddMenuEntry("4",11);  
  880.     glutAddMenuEntry("6",12);  
  881.     glutAddMenuEntry("8",13);  
  882.     glutAddMenuEntry("10",14);  
  883.     glutAddMenuEntry("12",15);  
  884.     glutAddMenuEntry("14",16);  
  885.     glutAddMenuEntry("16",17);  
  886.     glutAddMenuEntry("18",18);  
  887.     glutAddMenuEntry("20",19);  
  888.     glutAddMenuEntry("22",20);  
  889.     int Choice=glutCreateMenu(ProcessMenu);  
  890.     glutAddSubMenu("水平方向方格数",SetWidth);  
  891.     glutAddSubMenu("垂直方向方格数",SetHeight);  
  892.     glutCreateMenu(ProcessMenu);  
  893.     glutAddSubMenu("设置",Choice);  
  894.     glutAttachMenu(GLUT_RIGHT_BUTTON);  
  895. }  
  896.   
  897.   
  898. int main(int argc, char *argv[])  
  899. {     
  900.     InitMap();  
  901.     glutInit(&argc,argv);  
  902.     glutInitDisplayMode(GLUT_RGB|GLUT_SINGLE);  
  903.     glutInitWindowPosition(0, 0);  
  904.     glutInitWindowSize(1000, 600);  
  905.     glutCreateWindow("遗传算法在方格中的求最短路径动画演示");  
  906.     glutDisplayFunc(Display);  
  907.     glutReshapeFunc(ChangeSize);  
  908.     glutMouseFunc(MousePlot);  
  909.     MyCreateMenu();  
  910.     init();  
  911.     glutMainLoop();       
  912.     return 0;  
  913. }  

posted on 2015-05-19 10:43  moffis  阅读(492)  评论(0编辑  收藏  举报

导航