NYOJ 523 亡命逃窜( bfs )
#include<iostream>
#include<cstdio>
#include<queue>
#include<memory.h>
using namespace std;
struct point{
int a,b,c,time;
}p1,p2,p3;
int A,B,C,t,map[52][52][52];
int dir[][3] = {0,0,1, 0,0,-1, 0,1,0, 0,-1,0, 1,0,0,-1,0,0 };
int bfs(int x, int y, int z)
{
queue<point> q;
p1.a = x; p1.b = y; p1.c = z;
p1.time = 0;
q.push(p1);
while(!q.empty())
{
p1 = q.front();
q.pop();
if(p1.a == A && p1.b == B && p1.c ==C)
return p1.time;
for(int i = 0; i < 6; ++i)
{
p2.a = p1.a + dir[i][0];
p2.b = p1.b + dir[i][1];
p2.c = p1.c + dir[i][2];
p2.time = p1.time + 1;
if(p2.a < 0 || p2.a > A+1 || p2.b < 0 || p2.b > B+1 || p2.c < 0 || p2.c > C+1)
continue;
if(map[p2.a][p2.b][p2.c] == 0)
{
map[p2.a][p2.b][p2.c] = 1;
q.push(p2);
}
}
}
return -1;
}
int main()
{
// freopen("in.txt","r",stdin);
int i,j,k,T;
scanf("%d",&T);
while(T--)
{
memset(map,1,sizeof(map));
scanf("%d%d%d%d",&A,&B,&C,&t);
for(i = 1; i <= A; ++i)
for(j = 1; j <= B; ++j)
for(k = 1; k <= C; ++k)
scanf("%d",&map[i][j][k]);
if(map[i][j][k] == 1) //出口为1
{
printf("-1\n");
continue;
}
map[1][1][1] = 1;
int t1 = bfs(1,1,1);
t = t1 > t ? -1 : t1;
printf("%d\n",t);
}
return 0;
}
#include<cstdio>
#include<queue>
#include<memory.h>
using namespace std;
struct point{
int a,b,c,time;
}p1,p2,p3;
int A,B,C,t,map[52][52][52];
int dir[][3] = {0,0,1, 0,0,-1, 0,1,0, 0,-1,0, 1,0,0,-1,0,0 };
int bfs(int x, int y, int z)
{
queue<point> q;
p1.a = x; p1.b = y; p1.c = z;
p1.time = 0;
q.push(p1);
while(!q.empty())
{
p1 = q.front();
q.pop();
if(p1.a == A && p1.b == B && p1.c ==C)
return p1.time;
for(int i = 0; i < 6; ++i)
{
p2.a = p1.a + dir[i][0];
p2.b = p1.b + dir[i][1];
p2.c = p1.c + dir[i][2];
p2.time = p1.time + 1;
if(p2.a < 0 || p2.a > A+1 || p2.b < 0 || p2.b > B+1 || p2.c < 0 || p2.c > C+1)
continue;
if(map[p2.a][p2.b][p2.c] == 0)
{
map[p2.a][p2.b][p2.c] = 1;
q.push(p2);
}
}
}
return -1;
}
int main()
{
// freopen("in.txt","r",stdin);
int i,j,k,T;
scanf("%d",&T);
while(T--)
{
memset(map,1,sizeof(map));
scanf("%d%d%d%d",&A,&B,&C,&t);
for(i = 1; i <= A; ++i)
for(j = 1; j <= B; ++j)
for(k = 1; k <= C; ++k)
scanf("%d",&map[i][j][k]);
if(map[i][j][k] == 1) //出口为1
{
printf("-1\n");
continue;
}
map[1][1][1] = 1;
int t1 = bfs(1,1,1);
t = t1 > t ? -1 : t1;
printf("%d\n",t);
}
return 0;
}