NYOJ 523
法一:
#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;
int map[55][55][55],f[]={1,-1,0,0,0,0},g[]={0,0,1,-1,0,0},w[]={0,0,0,0,1,-1};
bool vis[55][55][55],flag;
struct Node
{
int x,y,z,step;
};
int bfs(int a,int b,int c,int time)
{
int i,j,k;
int r,s,t;
memset(vis,0,sizeof(vis));
queue <Node> q;
Node temp={0,0,0,time};
vis[0][0][0]=1;
q.push(temp);
while(!q.empty())
{
temp=q.front();
q.pop();
for(i=0;i<6;i++)
{
r=temp.x+f[i];
s=temp.y+g[i];
t=temp.z+w[i];
if(r>=0&&r<a&&s>=0&&s<b&&t>=0&&t<c&&vis[r][s][t]==0)
{
if(r==a-1&&s==b-1&&t==c-1&&map[r][s][t]==0&&temp.step-1>=0)
{
flag=1;
break;
}
else if(map[r][s][t]==0&&temp.step-1)
{
Node next={r,s,t,temp.step-1};
q.push(next);
vis[r][s][t]=1;
}
}
}
if(flag==1||temp.step-1==0)
break;
}
while(!q.empty())
q.pop();
return time-(temp.step-1);
}
int main()
{
int a,b,c;
int i,j,k,T;
int time;
scanf("%d",&T);
while(T--)
{
memset(map,0,sizeof(map));
flag=0;
scanf("%d%d%d%d",&a,&b,&c,&time);
for(k=0;k<a;k++)
{
for(i=0;i<b;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&map[k][i][j]);
}
}
}
int cnt=bfs(a,b,c,time);
if(flag==1)
printf("%d\n",cnt);
else
printf("-1\n");
}
return 0;
}
法二:
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
#include<algorithm>
using namespace std;
const int N = 55;
const int dir[6][3] = {{0, 0, 1}, {0, 0, -1}, {-1, 0, 0}, {1, 0, 0}, {0, 1, 0}, {0, -1, 0}};
struct node
{
int x, y, z;
int ceng;
}que[50000];
int maze[N][N][N];
int a, b, c, t;
int num;
int head, tail;
int Scan()
{
int res = 0 , ch;
while( !( ( ch = getchar() ) >= '0' && ch <= '9' ) )
{
if( ch == EOF ) return 1 << 30 ;
}
res = ch - '0' ;
while( ( ch = getchar() ) >= '0' && ch <= '9' )
res = res * 10 + ( ch - '0' ) ;
return res ;
}
int BFS()
{
node cur;
cur.x = 1, cur.y = 1, cur.z = 1, cur.ceng = 0;
maze[cur.x][cur.y][cur.z] = 0;
que[tail++] = cur;
while(head < tail)
{
node temp = que[head++];
if(temp.ceng > t) //无法到达
return -1;
if(temp.x == a && temp.y == b && temp.z == c && temp.ceng <= t)
return temp.ceng;
for(int i = 0; i < 6; ++i)
{
node now;
now.x = temp.x + dir[i][0]; now.y = temp.y + dir[i][1]; now.z = temp.z + dir[i][2];
if(maze[now.x][now.y][now.z])
{
now.ceng = temp.ceng + 1;
que[tail++] = now;
maze[now.x][now.y][now.z] = 0;
}
}
}
return -1;
}
int main()
{
int ncase;
ncase = Scan();
while(ncase--)
{
num = head = tail = 0;
memset(maze, 0, sizeof(maze));
a = Scan(), b = Scan(), c = Scan(), t = Scan();
for(int i = 1; i <= a; ++i)
for(int j = 1; j <= b; ++j)
for(int k = 1; k <= c; ++k)
{
maze[i][j][k] = Scan() ^ 1;
num += maze[i][j][k];
}
if(maze[a][b][c] == 0 || num < a + b + c - 3) //终点无法走
{
printf("-1\n");
continue;
}
printf("%d\n", BFS());
}
return 0;
}