迷宮最短路徑演算法(使用隊列)

來源:互聯網
上載者:User

    (上接迷宮遞迴演算法)

    順便也把圖裡求迷宮最短路徑演算法貼出來,主要思想是利用隊列,採用廣度優先搜尋法,當第一次出現目的點時,中斷搜尋,並輸出路徑。程式還是主要使用的C語言,對於隊列操作我又重寫了下基本作業碼比如入隊、出隊等,沒辦法對C++不熟啊!!

   個人認為需要說明的是:

   1. 為了記錄路徑,借鑒了樹的雙親標記法,所以隊列中的數組元素定義如下

   

typedef struct  ...{
    int location;     //(x-1)*3+y 
    int parent;       //記錄上一個節點即路徑中前驅節點,方便最後輸出
}QueueNode;

 

   2.仍然採用了上面的映射思想,公式也是 location=(x-1)*3+y

  

void Maze_Shortest(int maze[][5],point &start,point &des)
...{
    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)&&!FindFlag)
    ...{
        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][1];
            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;
        }
    
    }
    

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.