POJ_1253胜利的大逃亡
生活随笔
收集整理的這篇文章主要介紹了
POJ_1253胜利的大逃亡
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
??? 這道題使用BFS做的,剛開(kāi)始有點(diǎn)不太理解為什么使用隊(duì)列,一旦遇到可以到達(dá)終點(diǎn)的節(jié)點(diǎn)就立即返回,找到最短時(shí)間,最后明白了,因?yàn)樵陉?duì)列里的所有節(jié)點(diǎn)一定比隊(duì)頭節(jié)點(diǎn)
的時(shí)間長(zhǎng)。下面是具體代碼:
?
#include<stdio.h> #include<queue> using namespace std; typedef struct{ int x,y,z,steps; }point; point start,end; int a,b,c,t,n; int map[51][51][51]; int dir[6][3]={{1,0,0}, {-1,0,0}, {0,1,0}, {0,-1,0}, {0,0,1}, {0,0,-1}}; int bfs(point start){ queue<point>q; int i; point cur,next; if(start.x==a-1&&start.y==b-1&&start.z==c-1)//考慮起點(diǎn)和終點(diǎn)相同的情況 { return 0; } start.steps=0; map[start.x][start.y][start.z]=1; q.push(start); while(!q.empty()) { cur=q.front();//取隊(duì)首元素 q.pop(); for(i=0;i<6;i++) //廣度優(yōu)先搜索 { next.x=cur.x+dir[i][0]; next.y=cur.y+dir[i][1]; next.z=cur.z+dir[i][2]; if(next.x==a-1 && next.y==b-1 && next.z==c-1) //下一步就是目的地 { return cur.steps+1; }if(next.x>=0&&next.x<a&&next.y>=0&&next.y<b&&next.z>=0&&next.z<c) if(map[next.x][next.y][next.z]!=1) { map[next.x][next.y][next.z]=1; next.steps=cur.steps+1; q.push(next); } } } return -1; } int main() { int i,j,k,step; scanf("%d\n",&n); while(n--) { scanf("%d %d %d %d",&a,&b,&c,&t); for(i=0;i<a;i++) for(j=0;j<b;j++) for(k=0;k<c;k++) scanf("%d",&map[i][j][k]); if(a+b+c-3>t) {printf("-1\n");continue; } if(map[a-1][b-1][c-1]==1){printf("-1\n");continue;}start.x=0; start.y=0; start.z=0;step=bfs(start); if(step>=0&&step<=t) printf("%d\n",step); else printf("-1\n"); } return 0; }?
轉(zhuǎn)載于:https://www.cnblogs.com/tianfeng/archive/2013/05/31/bfs.html
總結(jié)
以上是生活随笔為你收集整理的POJ_1253胜利的大逃亡的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: idea中maven项目中引入第三方ji
- 下一篇: 多包管理工具lerna