六个方向广搜...先是knowledgetime的代码,我写了一遍能A、、、
#include <stdio.h>
#include <string.h>
#define Msize 29800
typedef struct Dungeon
{
int x,y,z,d;
};
const int step[10][3]={{-1,0,0},{1,0,0},{0,-1,0},{0,1,0},{0,0,-1},{0,0,1}};
Dungeon q[Msize]={0};
int L,R,C,mat[40][40][40]={0},mins;
bool vis[40][40][40]={false};
int sx,sy,sz,ex,ey,ez;
char s[40]={'\0'};
void bfs()
{
int head=0,tail=1,hx,hy,hz;
q[0].x=sx;
q[0].y=sy;
q[0].z=sz;
q[0].d=0;
vis[sx][sy][sz]=true;
while(head<tail)
{
for(int i=0;i<6;i++)
{
hx=q[head].x+step[i][0];
hy=q[head].y+step[i][1];
hz=q[head].z+step[i][2];
if(0<hx&&hx<=L && 0<hy&&hy<=R && 0<hz&&hz<=C && mat[hx][hy][hz] && !vis[hx][hy][hz])
{
if(hx==ex && hy==ey && hz==ez)
{
mins=q[head].d+1;
return;
}
q[tail].x=hx;
q[tail].y=hy;
q[tail].z=hz;
q[tail++].d=q[head].d+1;
vis[hx][hy][hz]=true;
}
}
head++;
}
}
int main()
{
while(scanf("%d %d %d",&L,&R,&C)==3)
{
if(L+R+C==0) break;
getchar();
memset(mat,0,sizeof(mat));
memset(vis,false,sizeof(vis));
for(int i=1;i<=L;i++)
for(int j=1;j<=R;j++)
{
scanf("%s",s);
for(int k=1;k<=C;k++)
if(s[k-1]=='S')
{ sx=i; sy=j; sz=k; }
else if(s[k-1]=='E')
{ ex=i; ey=j; ez=k; mat[i][j][k]=1; }
else if(s[k-1]=='.')
mat[i][j][k]=1;
}
mins=-1;
bfs();
if(mins<0) printf("Trapped!\n");
else printf("Escaped in %d minute(s).\n",mins);
}
return 0;
}
这个代码是我自己写的,始终过不了,莫名其妙地RE!!!
#include<cstdio>
#include<cstring>
#include<cstdlib>
#define MAXL 40
int L, R, C, SX, SY, SZ, EX, EY, EZ;
char str[MAXL];
bool vis[MAXL][MAXL][MAXL];
int d[MAXL][MAXL][MAXL];
int qx[50000], qy[50000], qz[50000];
int dx[] = { 1, -1, 0, 0, 0, 0};
int dy[] = { 0, 0, -1, 1, 0, 0};
int dz[] = { 0, 0, 0, 0, 1, -1};
bool judge( int a, int b, int c)
{
if( a < 1 || b < 1 || c < 1 || a > L || b > R || c > C || !vis[a][b][c])
return false;
return true;
}
void init()
{
memset( d, -1, sizeof d);
memset( vis, false, sizeof vis);
for( int i = 1; i <= L; i ++)
{
for( int j = 1; j <= R; j ++)
{
scanf( "%s", str);
for( int k = 1; k <= C; k ++)
{
if( str[k - 1] == 'S' || str[k - 1] == 'E' || str[k - 1] == '.')
vis[i][j][k] = true;
if( str[k - 1] == 'S')
{
SX = i;
SY = j;
SZ = k;
}
if( str[k - 1] == 'E')
{
EX = i;
EY = j;
EZ = k;
}
}
}
}
}
void bfs()
{
int x, y, z;
int front = 0, rear = 0;
d[SX][SY][SZ] = 0;
qx[rear] = SX;
qy[rear] = SY;
qz[rear] = SZ;
rear ++;
while( front < rear)
{
x = qx[front];
y = qy[front];
z = qz[front];
front ++;
vis[x][y][z] = false;
if( x == EX && y == EY && z == EZ)
return;
for( int i = 0; i < 6; i ++)
{
int nx = x + dx[i];
int ny = y + dy[i];
int nz = z + dz[i];
bool yes = judge( nx, ny, nz);
if( yes)
{
qx[rear] = nx;
qy[rear] = ny;
qz[rear] = nz;
rear ++;
d[nx][ny][nz] = d[x][y][z] + 1;
}
}
}
}
int main()
{
while( scanf( "%d%d%d", &L, &R, &C) == 3)
{
getchar();
if( L + R + C == 0) break;
init();
bfs();
int ok = d[EX][EY][EZ];
if( ok < 0)
printf( "Trapped!\n");
else
printf( "Escaped in %d minute(s).\n", ok);
}
return 0;
}