您的位置:首页 > 其它

ZOJ 1940 Dungeon Master

2015-02-14 22:04 295 查看
这题是3维的搜索题。用BFS就可以。只能上下左右前后六个方位,所以方向数组就是dir[6][3]={{1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1}};

要注意有可能到不了的情况。

#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
int l,r,c,x1,y1,z1,ma[31][31][31],dir[6][3]={{1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1}};
struct point
{
int x,y,z,cost;
};
int BFS(int x,int y,int z)
{
point a;
a.x=x;
a.y=y;
a.z=z;
a.cost=0;
ma[x][y][z]=1;
queue<point> q;
q.push(a);
while(!q.empty())
{
point t=q.front();
q.pop();
for(int i=0;i<6;i++)
{
point w;
w.x=t.x+dir[i][0];
w.y=t.y+dir[i][1];
w.z=t.z+dir[i][2];
w.cost=t.cost+1;
if(w.x>=0&&w.x<l&&w.y>=0&&w.y<r&&w.z>=0&&w.z<c&&ma[w.x][w.y][w.z]==0)
{
ma[w.x][w.y][w.z]=1;
q.push(w);
if(w.x==x1&&w.y==y1&&w.z==z1) return w.cost;
}
}

}
return -1;
}
int main()
{
int tx,ty,tz;
while(scanf("%d%d%d",&l,&r,&c)!=EOF)
{
getchar();
if(l==0&&r==0&&c==0) break;
memset(ma,0,sizeof(ma));
for(int i=0;i<l;i++)
{
for(int j=0;j<r;j++)
{
for(int k = 0 ; k < c ; k++)
{
char c;
scanf("%c",&c);
if(c=='#') ma[i][j][k]=1;
else if(c=='S')
{
tx=i;
ty=j;
tz=k;
}
else if(c=='E')
{
x1 = i;
y1 = j;
z1 = k;
}
}
getchar();
}
getchar();
}
int ans = BFS(tx,ty,tz);
if(ans==-1) printf("Trapped!\n");
else
printf("Escaped in %d minute(s).\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  acm bfs