迷宮最短路徑的C++實現(隊列:廣度優先)

來源:互聯網
上載者:User
#include<iostream>#include<queue>#include<string>using namespace std;struct point{int x;int y;point *last;//上一步的座標};int main(){while(1){int row, col, i, j;cout<<"請輸入迷宮圖的行數和列數:";cin>>row>>col;int **a = new int* [row+2];for(i = 0; i < row+2; ++i){a[i] = new int[col+2];}cout<<"請輸入迷宮圖(1代表牆壁,0代表通路):"<<endl;for(i = 1; i < row+1; ++i){for(j = 1; j < col+1; ++j){cin>>a[i][j];}}for(i = 0; i < col+2; ++i){//加牆a[0][i] = 1;a[row+1][i] = 1;}for(i = 1; i < row+1; ++i){//加牆a[i][0] = 1;a[i][col+1] = 1;}queue<point*> q;point *start = (point*)malloc(sizeof(point));//起點cout<<"請輸入起點座標(範圍1,1到"<<row<<","<<col<<"):";cin>>start->x>>start->y;start->last = start;q.push(start);a[start->x][start->y] = 2;point end;//終點cout<<"請輸入終點座標(範圍1,1到"<<row<<","<<col<<"):";cin>>end.x>>end.y;int aspect[4][2] = {{0, -1},{0, 1},{-1, 0},{1, 0}};//轉向:上下左右int flag = 0;//是否有路可走的標誌while(!q.empty()){point *front = q.front();q.pop();//彈出隊頭if(front->x == end.x && front->y == end.y){flag = 1;cout<<"成功找到出路."<<"最少需要"<<a[front->x][front->y]-2<<"步。如下所示:"<<endl;a[front->x][front->y] = -6;//cout<<"倒退回去:"<<(front)->x<<","<<(front)->y;point *lastPoint = front;front = front->last;while((front->x != start->x) || (front->y != start->y)){//cout<<"->"<<front->x<<","<<front->y;if(lastPoint->x - front->x == 1){a[front->x][front->y] = -1;}else if(lastPoint->x - front->x == -1){a[front->x][front->y] = -2;}else if(lastPoint->y - front->y == 1){a[front->x][front->y] = -3;}else{a[front->x][front->y] = -4;}lastPoint = front;front = front->last;}//cout<<"->"<<start->x<<","<<start->y<<endl;a[start->x][start->y] = -5;break;}else{for(int i = 0; i < 4 ; ++i){point *temp = new point;temp->x = front->x + aspect[i][0];temp->y = front->y + aspect[i][1];if(a[temp->x][temp->y] == 0){temp->last = front;q.push(temp);a[temp->x][temp->y] = a[front->x ][front->y] + 1;}}}}if(!flag)cout<<"無路可走!"<<endl;else{string s[6] = {"★", "☆", "←","→","↑","↓" };for(int i = 0; i < 11; ++i){for(int j = 0; j < 10; ++j){if(a[i][j]==1){cout<<"■";}else if(a[i][j]<0){int temp = a[i][j]+6;cout<<s[temp];}else{cout<<"  ";}}cout<<endl;}}system("pause");}}

測試資料

9 80 0 1 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 1 1 1 0 0 1 1 1 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 1 0 1 0 1 1 1 1 0 0 1 1 1 0 0 0 0 0 10 0 0 0 0 0 0 0 

運行結果:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.