zoj 1438 - Asteroids!

http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1438

还是很经典的搜索题,有意思的是把原来的二维迷宫改为了立体迷宫,用三维数组来存储。易错的是三维容易把坐标弄错,我因为这wa了好多次。。。在纸上多画画就ok。

代码如下:

#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;

int dx[] = {-1, 1, 0, 0, 0, 0};
int dy[] = { 0, 0, 1, -1, 0, 0};
int dz[] = { 0, 0, 0, 0, -1, 1};

int N;
char path[15][15][15];
char s[6];
int vis[15][15][15];
typedef struct
{
int x;
int y;
int z;
int step;
}State;
State begin, end;
queue<State> q;

int final(State s1, State s2)
{
if(s1.x == s2.x && s1.y == s2.y && s1.z == s2.z)
return 1;
return 0;
}

int isright(State u)
{
if(u.x >= 0 && u.x < N && u.y >= 0 && u.y < N && u.z >= 0 && u.z < N)
return 1;
return 0;
}

int main()
{
int i, j, k, ok;
while(scanf("%s%d", s, &N) != EOF)
{
getchar();
for(i = 0; i < N; i++)
for(j = 0; j < N; j++)
{
scanf("%s", path[i][j]);
}
scanf("%d%d%d", &begin.x, &begin.y, &begin.z);
scanf("%d%d%d", &end.x, &end.y, &end.z);
scanf("%s", s);
memset(vis, 0, sizeof(vis));
ok = 0;
begin.step = 0;
vis[begin.z][begin.y][begin.x] = 1;
q.push(begin);
while(!q.empty())
{
State u = q.front();
q.pop();
if(final(u, end))
{
ok = 1;
printf("%d %d\n", N, u.step);
break;
}
for(i = 0; i < 6; i++)
{
State v;
v.step = u.step + 1;
v.x = u.x + dx[i];
v.y = u.y + dy[i];
v.z = u.z + dz[i];
if(path[v.z][v.y][v.x] != 'X' && isright(v) && !vis[v.z][v.y][v.x])
{
q.push(v);
vis[v.z][v.y][v.x] = 1;
}
}
}
if(!ok)
printf("NO ROUTE\n");
while(!q.empty())
q.pop();
}
return 0;
}

 

你可能感兴趣的:(ZOJ)