您的位置:首页 > 其它

POJ2251

2016-07-07 11:26 417 查看
//BFS找最短路径
//可以向上下左右前后六个方向搜索
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <queue>
using namespace std ;
int dir[6][3]= {{1,0,0},{-1,0,0},{0,-1,0},{0,1,0},{0,0,1},{0,0,-1}};
char MAP[32][32][32] ;
int visit[32][32][32] ;
int L , R , C ;
int tl,tr,tc;
int cnt;
struct node
{
int r ;
int c ;
int l ;
int step;
}M;
int BFS()
{
queue<node> q;
int ll , rr , cc ;
M.l=tl;
M.r=tr;
M.c=tc;
M.step=0;
visit[tl][tc]=1;
q.push(M);
while(!q.empty())
{
node now;
now=q.front();
q.pop();
for(int i = 0 ;i<6;i++)
{
ll=now.l+dir[i][0];
rr=now.r+dir[i][1];
cc=now.c+dir[i][2];
if(ll>0&&ll<=L&&rr>0&&rr<=R&&cc>0&&cc<=C&&!visit[ll][rr][cc])
{
if(MAP[ll][rr][cc]=='E')
{
cnt=now.step+1;
return cnt;
}
if(MAP[ll][rr][cc]=='.')
{
node temp;
temp.l=ll;
temp.r=rr;
temp.c=cc;
temp.step=now.step+1;
visit[ll][rr][cc]=1;
q.push(temp);
}
}
}
}
return 0 ;
}
int main()
{
char str[10];
while(cin >> L >> R >> C)
{
if(!L && !R && !C) break ;
for(int i = 1 ; i <= L ; i ++)
{
for(int j = 1 ; j <= R ; j ++)
{
for(int k = 1 ; k <= C ; k ++)
{
cin >> MAP[i][j][k] ;
if(MAP[i][j][k]=='S')
{
tl=i;
tr=j;
tc=k;
}
}
}
}
getchar();
getchar();
memset(visit , 0 , sizeof(visit)) ;
cnt = 0 ;
int ans = BFS();
if(ans==0) printf("Trapped!\n");
else printf("Escaped in %d minute(s).\n",ans);
}
return 0 ;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: