Problem Description
蓝色空间号和万有引力号进入了四维水洼,发现了四维物体--魔戒。
这里我们把飞船和魔戒都抽象为四维空间中的一个点,分别标为 "S" 和 "E"。空间中可能存在障碍物,标为 "#",其他为可以通过的位置。
现在他们想要尽快到达魔戒进行探索,你能帮他们算出最小时间是最少吗?我们认为飞船每秒只能沿某个坐标轴方向移动一个单位,且不能越出四维空间。
Input
输入数据有多组(数据组数不超过 30),到 EOF 结束。
每组输入 4 个数 x, y, z, w 代表四维空间的尺寸(1 <= x, y, z, w <= 30)。
接下来的空间地图输入按照 x, y, z, w 轴的顺序依次给出,你只要按照下面的坐标关系循环读入即可。
for 0, x-1
for 0, y-1
for 0, z-1
for 0, w-1
保证 "S" 和 "E" 唯一。
Output
对于每组数据,输出一行,到达魔戒所需的最短时间。
如果无法到达,输出 "WTF"(不包括引号)。
Sample Input
2 2 2 2
..
.S
..
#.
#.
.E
.#
..
2 2 2 2
..
.S
#.
##
E.
.#
#.
..
Sample Output
1
3
普普通通的BFS 只不过是个四维数组,
不过 我们来聊一聊方向数组;
首先 bfs的感觉就是把这一层的全搞完再进到下一层(摘自别的博文)
故:每次需要遍历该点的周围
怎样实现 ,这时就需要用方向数组了,
对于该类型题(一般的只需要找最近的一周),
方向数组有以下规律:
沿p(p为x,y,z,w等坐标轴)轴 上移一步 以及 下移一步 ,沿其余轴不动
对于一个含n个元素的数组a a0a1a2a3..an-1 有2n种情况 :
任取i (0<=i<n) ai=1 或 ai=-1
则 对于任意j (0<=j<n) if(i!=j) aj = 0
#include <map>
#include <set>
#include <list>
#include <cmath>
#include <stack>
#include <queue>
#include <deque>
#include <cstdio>
#include <vector>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#define eps 1e-8
#define PI acos(-1)
#define INF 0x3f3f3f3f
using namespace std;
const int N=40;
typedef long long LL;
const int dir[4][2]= { {1,0},{0,1},{-1,0},{0,-1} };
const int dir4[8][4]= { {1,0,0,0},{-1,0,0,0},{0,1,0,0},{0,-1,0,0},{0,0,1,0},{0,0,-1,0},{0,0,0,1},{0,0,0,-1} };
int GCD(int a,int b)
{
return b ? GCD(b,a%b) : a;
}
char state[N][N][N][N];
int vis[N][N][N][N];
int sta[4];
int n,m,r,t;
struct NODE
{
int x,y,z,w,cou;
};
void myclear(queue<NODE> &p)
{
queue<NODE>q;
swap(p,q);
return ;
}
int check(struct NODE a)
{
if(a.x<0 || a.x>=n || a.y<0 || a.y>=m || a.z<0 || a.z>=r || a.w<0 || a.w>=t )
return 0;
if(vis[a.x][a.y][a.z][a.w]==1)
return 0;
if(state[a.x][a.y][a.z][a.w]=='#')
return 0;
return 1;
}
int BFS(int x,int y,int z,int w)
{
queue<NODE>p;
struct NODE t,now;
int i;
now.x=x;
now.y=y;
now.z=z;
now.w=w;
now.cou=0;
vis[x][y][z][w]=1;
p.push(now);
while(!p.empty())
{
t=p.front();
p.pop();
if(state[t.x][t.y][t.z][t.w]=='E')
{
return t.cou;
}
for(i=0; i<8; i++)
{
now.x=t.x+dir4[i][0];
now.y=t.y+dir4[i][1];
now.z=t.z+dir4[i][2];
now.w=t.w+dir4[i][3];
if(check(now))
{
now.cou=t.cou+1;
p.push(now);
vis[now.x][now.y][now.z][now.w]=1;
}
}
}
//myclear(p);
p=queue<NODE>();
return -1;
}
int main()
{
while(scanf("%d%d%d%d",&n,&m,&r,&t)!=EOF)
{
memset(vis,0,sizeof(vis));
memset(state,0,sizeof(state));
int i,j,k,l,ans=0;
for(i=0; i<n; i++)
for(j=0; j<m; j++)
for(k=0; k<r; k++)
for(l=0; l<t; l++)
{
scanf(" %c",&state[i][j][k][l]);
if(state[i][j][k][l]=='S')
{
sta[0]=i;
sta[1]=j;
sta[2]=k;
sta[3]=l;
}
}
ans=BFS(sta[0],sta[1],sta[2],sta[3]);
if(ans==-1)
printf("WTF\n");
else
printf("%d\n",ans);
}
return 0;
}
代码里写了队列的两种清空方法
649

被折叠的 条评论
为什么被折叠?



