(简单) POJ 3984 迷宫问题,BFS。
生活随笔
收集整理的這篇文章主要介紹了
(简单) POJ 3984 迷宫问题,BFS。
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Description
定義一個二維數組:int maze[5][5] = {
0, 1, 0, 0, 0,
0, 1, 0, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
};
它表示一個迷宮,其中的1表示墻壁,0表示可以走的路,只能橫著走或豎著走,不能斜著走,要求編程序找出從左上角到右下角的最短路線。 水題,BFS然后記錄路徑就好。 代碼如下: #include<iostream> #include<cstring> #include<queue> #include<utility>using namespace std;typedef struct pair<int,int> pii;int vis[6][6]; int fa[6][6];bool judge(int x,int y) {if(x<0||y<0||x>4||y>4)return 0;if(vis[x][y])return 0;return 1; }void slove() {queue < pii > que;pii temp,temp1;int t1,t2;que.push(make_pair(0,0));vis[0][0]=1;while(!que.empty()){temp=que.front();que.pop();t1=temp.first/5;t2=temp.first%5;fa[t1][t2]=temp.second;if(t1==4&&t2==4)return;--t1;if(judge(t1,t2)){vis[t1][t2]=1;temp1=make_pair(t1*5+t2,temp.first);que.push(temp1);}t1+=2;if(judge(t1,t2)){vis[t1][t2]=1;que.push(make_pair(t1*5+t2,temp.first));}--t1;--t2; if(judge(t1,t2)){vis[t1][t2]=1;que.push(make_pair(t1*5+t2,temp.first));} t2+=2;if(judge(t1,t2)){vis[t1][t2]=1;que.push(make_pair(t1*5+t2,temp.first));}} }void showans() {int cou=0;int ans[30];int temp=24;while(temp){ans[cou++]=temp;temp=fa[temp/5][temp%5];}cout<<"(0, 0)"<<endl;for(int i=cou-1;i>=0;--i)cout<<'('<<ans[i]/5<<", "<<ans[i]%5<<')'<<endl; }int main() {ios::sync_with_stdio(false);while(cin>>vis[0][0]){for(int j=1;j<5;++j)cin>>vis[0][j];for(int i=1;i<5;++i)for(int j=0;j<5;++j)cin>>vis[i][j];slove();showans();} return 0; } View Code
?
轉載于:https://www.cnblogs.com/whywhy/p/4229923.html
總結
以上是生活随笔為你收集整理的(简单) POJ 3984 迷宫问题,BFS。的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: FastDFS 安装
- 下一篇: 学习总结——Selenium元素定位