POJ2251 Dungeon Master
http://poj.org/problem?id=2251
题意:
三维空间,求从S点到E点的最小距离。思路:
简单bfs搜索,从起点开始压入队列逐渐广搜开直到找到E或者队列为空,注意标记走过的位置。
解题代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
int L,R,C;
struct node
{
int x,y,z,step;
}start,end;
int d[6][3]={1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1};
int a[35][35][35];
bool b[35][35][35];
int bfs(node start,node end)
{
int flag=0;
queue<node> q;
while(!q.empty())
q.pop();
node no;
no.x=start.x;
no.y=start.y;
no.z=start.z;
no.step=0;
q.push(no);
while(!q.empty())
{
node c=q.front();
q.pop();
if(c.x==end.x&&c.y==end.y&&c.z==end.z)
{
flag=c.step;
return flag;
}
for(int i=0;i<6;i++)
{
node sta;
sta.x=c.x+d[i][0];
sta.y=c.y+d[i][1];
sta.z=c.z+d[i][2];
sta.step=c.step+1;
if(sta.x<0||sta.x>=L||sta.y<0||sta.y>=R||sta.z<0||sta.z>=C)
continue;
if(a[sta.x][sta.y][sta.z]==1&&!b[sta.x][sta.y][sta.z])
{
b[sta.x][sta.y][sta.z]=true;
q.push(sta);
}
}
}
return flag;
}
int main()
{
char s[35];
int d;
while(scanf("%d%d%d",&L,&R,&C)!=EOF)
{
if(L==0||R==0||C==0)
break;
d=0;
memset(a,0,sizeof(a));
memset(b,false,sizeof(b));
for(int i=0;i<L;i++)
for(int j=0;j<R;j++)
{
scanf("%s",s);
for(int k=0;k<C;k++)
{
if(s[k]=='S')
{
start.x=i;
start.y=j;
start.z=k;
}
if(s[k]=='E')
{
end.x=i;
end.y=j;
end.z=k;
a[i][j][k]=1;
}
if(s[k]=='.')
a[i][j][k]=1;
}
}
d=bfs(start,end);
if(d!=0)
printf("Escaped in %d minute(s).\n",d);
else
printf("Trapped!\n");
}
return 0;
}
注意:必须使用队列进行bfs搜索,我尝试直接通过bfs函数递推bfs搜索,但出错了。