胜利大逃亡
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 38775 Accepted Submission(s): 13641
魔王住在一个城堡里,城堡是一个A*B*C的立方体,可以被表示成A个B*C的矩阵,刚开始Ignatius被关在(0,0,0)的位置,离开城堡的门在(A-1,B-1,C-1)的位置,现在知道魔王将在T分钟后回到城堡,Ignatius每分钟能从一个坐标走到相邻的六个坐标中的其中一个.现在给你城堡的地图,请你计算出Ignatius能否在魔王回来前离开城堡(只要走到出口就算离开城堡,如果走到出口的时候魔王刚好回来也算逃亡成功),如果可以请输出需要多少分钟才能离开,如果不能则输出-1.
特别注意:本题的测试数据非常大,请使用scanf输入,我不能保证使用cin能不超时.在本OJ上请使用Visual C++提交.
1 3 3 4 20 0 1 1 1 0 0 1 1 0 1 1 1 1 1 1 1 1 0 0 1 0 1 1 1 0 0 0 0 0 1 1 0 0 1 1 0
11
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <queue>
using namespace std;
const int maxn=55;
int map[maxn][maxn][maxn],a,b,c,t;
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 used[maxn][maxn][maxn];
struct node{
int x,y,z,step;
};
bool islegal(int x, int y ,int z){
if (x<1 || y<1 || z<1 || x>a || y>b || z>c || map[x][y][z]==1) return 0;
return 1;
}
int bfs(){
queue<node>Q;
node q,p;
//第一个入队列的元素即为起点
p.x=1;
p.y=1;
p.z=1;
p.step=0;
used[1][1][1]=1;
Q.push(p);
while(!Q.empty()){
p=Q.front(); //取队列元素
Q.pop(); //弹出队首元素
if (p.x==a && p.y==b && p.z==c && p.step<=t) return p.step; //到达终点
for (int i=0;i<6;i++){ //6个方向搜索
q=p;
q.x+=dx[i];
q.y+=dy[i];
q.z+=dz[i];
if (!used[q.x][q.y][q.z] && (islegal(q.x,q.y,q.z))){
used[q.x][q.y][q.z]=1;
q.step=p.step+1;
if (abs(q.x-a)+abs(q.y-b)+abs(q.z-c)+q.step>t) continue;//最短距离都无法满足要求就放弃这个方向
Q.push(q);
}
}
}
return -1; //不存在方案便输出-1
}
int main(){
int k;
scanf("%d",&k);
while (k--){
scanf("%d %d %d %d",&a,&b,&c,&t);
for (int i=1;i<=a;i++)
for (int j=1;j<=b;j++)
for (int k=1;k<=c;k++)
scanf("%d",&map[i][j][k]);
memset(used,0,sizeof(used));
printf("%d\n",bfs());
}
return 0;
}
498



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



