本题难度并不大,一个普通的用BFS求解的题,值得注意的是数据的输入(三维数据输入被绕了几圈);还有就是最后的出口可以表示墙,无法出去(就是没考虑到这点WA了一次);剩下的就是BFS的常规思路及框架了。
- #include<cstdio>
- #include<vector>
- #include<queue>
- #include<cstring>
- using namespace std;
- const int len=50+10;
- int K,A,B,C,T;
- struct node{
- int x,y,z;
- node(int x1=0,int y1=0,int z1=0):x(x1),y(y1),z(z1){}
- };
- int d[len][len][len]; //从初始位置到当前位置的长度
- int p[len][len][len]; //输入数据的保存
- node n0,nt; //初始位置和最终位置
- void read(){
- scanf("%d%d%d%d",&A,&B,&C,&T);
- n0.x=0,n0.y=0,n0.z=B-1;
- nt.x=A-1,nt.y=C-1,nt.z=0;
- for(int x=0;x<A;x++)
- for(int z=B-1;z>=0;z--)
- for(int y=0;y<C;y++)
- scanf("%d",&p[x][y][z]);
- }
- const int dir[][3]={{0,0,1},{0,0,-1},{0,-1,0},{0,1,0},{1,0,0},{-1,0,0}}; //上下左右前后
- void print(const node &u){
- if(d[u.x][u.y][u.z]<=T)
- printf("%d\n",d[u.x][u.y][u.z]);
- else printf("-1\n");
- }
- bool isValid(const node &v){
- return v.x>=0 && v.x<A && v.y>=0 && v.y<C && v.z>=0 && v.z<B;
- }
- void bfs(){
- queue<node>q;
- q.push(n0);
- memset(d,0,sizeof(d));
- while(!q.empty()){
- node u=q.front();q.pop();
- if(u.x== nt.x && u.y== nt.y && u.z == nt.z){
- print(u);
- return ;
- }
- for(int i=0;i<6;i++){
- node v=node(u.x+dir[i][0],u.y+dir[i][1],u.z+dir[i][2]);
- if(d[v.x][v.y][v.z]==0 && isValid(v) && !p[v.x][v.y][v.z]){ //p[][][]=1时表示墙,不能放入队列中
- d[v.x][v.y][v.z]=d[u.x][u.y][u.z]+1;
- q.push(v);
- }
- }
- }
- printf("-1\n"); //这里值得注意,出口可以表示墙,此时无法出去,通过这条语句输出结果。
- }
- int main(){
- scanf("%d",&K);
- while(K--){
- read();
- bfs();
- }
- return 0;
- }