迷宮最短路徑演算法(使用佇列)
阿新 • • 發佈:2019-01-22
順便也把圖裡求迷宮最短路徑演算法貼出來,主要思想是利用佇列,採用廣度優先搜尋法,當第一次出現目的點時,中斷搜尋,並輸出路徑。程式還是主要使用的C語言,對於佇列操作我又重寫了下基本操作程式碼比如入隊、出隊等,沒辦法對C++不熟啊!!
個人認為需要說明的是:
1. 為了記錄路徑,借鑑了樹的雙親表示法,所以佇列中的陣列元素定義如下
typedef struct{int location; //(x-1)*3+y
int parent; //記錄上一個節點即路徑中前驅節點,方便最後輸出
}QueueNode;
2.仍然採用了上面的對映思想,公式也是 location=(x-1)*3+y
{
queue Queue;
InitializeQueue(Queue);
EnterQueue(Queue,(start.x-1)*5+start.y,Queue.head);
int direction;
bool FindFlag=false;
int dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
while (!EmptyQueue(Queue)
{
int curX=Queue.array[Queue.head].location/3+1;
int curY=Queue.array[Queue.head].location%3;
for (direction=0;direction<4;direction++) //遍歷該點四周四個鄰接點
{
int nextX=curX+dir[direction][0];
int nextY=curY+dir[direction][
if (!maze[nextX][nextY]) //如果為0 排除了牆和已經踩過的路
{
EnterQueue(Queue,(nextX-1)*3+nextY,Queue.head); //入隊,入隊元素是對映後節點!
if (nextX==des.x&&nextY==des.y)
{
FindFlag=true;
break;
}
}
}
Queue.head++;
}
if (EmptyQueue(Queue))
{
printf("找不到路徑 ");
}
if(FindFlag)
{
int pre=Queue.array[--Queue.rear].parent;
Queue.array[1].parent=0;
printf("%d<- ",Queue.array[Queue.rear].location);
while (pre) //迭代輸出路徑,可惜是逆向輸出,不過可以用棧解決
{
printf("%d<- ",Queue.array[pre].location);
pre=Queue.array[pre].parent;
}
}