6尋找迷宮的一條出路,1代表障礙,0代表通。算法描述:
這裏可以使用幾種方法,我知道的有使用《數據結構》上“窮舉求解”的方法,還有就是使用遺傳算法尋找最優路徑。這裏我先簡單描述下“窮舉求解”,然後再做遺傳算法的方式。
1 問題中要涉及走過路徑的回溯,因爲棧是先進後出,所以利於回溯,選擇棧來存儲走過路徑
2 每一步有四個方向可以走,每到一步依次判斷每一個方向,只要判斷到某個方向可走就選擇這個方向前進。
3 當所有方向都不能行進時,回溯到上一步,此時判斷棧頂指針是否爲-1,如果是,返回false失敗,否則遞歸調用繼續尋找。
C++源碼:
#include "stdafx.h" #include <stdio.h> #include <iostream> using namespace std; #define MAX_SIZE 10 int maze[MAX_SIZE][MAX_SIZE]= { {1,1,1,1,1,1,1,1,1,1}, {1,0,0,1,0,0,0,1,0,1}, {1,0,0,1,0,0,0,1,0,1}, {1,0,0,0,0,1,1,0,0,1}, {1,0,1,1,1,0,0,0,0,1}, {1,0,0,0,1,0,0,0,0,1}, {1,0,1,0,0,0,1,0,0,1}, {1,0,1,1,1,0,1,1,0,1}, {1,1,0,0,0,0,0,0,0,1}, {1,1,1,1,1,1,1,1,1,1} }; typedef struct { int x; int y; }POINT; typedef struct { POINT data[MAX_SIZE*MAX_SIZE]; int top; }STACK; bool operator != (POINT& point1,POINT& point2) { if(point1.x!=point2.x||point1.y!=point2.y) return true; else return false; } bool operator == (POINT& point1,POINT& point2) { if(point1.x==point2.x&&point1.y==point2.y) return true; else return false; } bool FindWay(int maze[][MAX_SIZE],POINT start,POINT end,STACK& way) { POINT step; step.x = start.x; step.y = start.y; if(way.data[way.top]!=end) { /************first,make sure the direction**********/ if(maze[step.y][step.x+1]==0) //east { maze[step.y][step.x] = 1; way.top++; way.data[way.top] = step; step.x++; FindWay(maze,step,end,way); } else if(maze[step.y+1][step.x]==0) //south { maze[step.y][step.x] = 1; way.top++; way.data[way.top] = step; step.y++; FindWay(maze,step,end,way); } else if(maze[step.y][step.x-1]==0) //west { maze[step.y][step.x] = 1; way.top++; way.data[way.top] = step; step.x--; FindWay(maze,step,end,way); } else if(maze[step.y-1][step.x]==0) //north { maze[step.y][step.x] = 1; way.top++; way.data[way.top] = step; step.y--; FindWay(maze,step,end,way); } else //There is no direction available { if(way.top<0) return false; else { maze[step.y][step.x] = 1; step = way.data[way.top]; way.top--; FindWay(maze,step,end,way); } }//end else }//end if else return true; } int main(int argc, char* argv[]) { POINT start,end; start.x = 1; start.y = 1; end.x = 8; end.y = 8; STACK way; way.top = -1; if(FindWay(maze,start,end,way)) { cout<<"Have found the way!"<<endl; for(int i=0;i<=way.top;i++) printf("(%d,%d) ",way.data[i].x,way.data[i].y); } else cout<<"Don't find the way!"<<endl; return 1; }
運行結果: