
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<stdio.h>
#include<queue>
using namespace std;
struct node
{
int x,y,z,steps;
friend bool operator<(node a,node b)
{
return a.steps>b.steps;
}
};
node start;
int a,b,c,t,n,ans;
int map[51][51][51];
int dir[6][3]={{1,0,0}, {-1,0,0}, {0,1,0}, {0,-1,0}, {0,0,1}, {0,0,-1}};
void bfs()
{
priority_queue<node>q;
int i;
node cur,next;
map[start.x][start.y][start.z]=1;
q.push(start);
while(!q.empty())
{
cur=q.top();//取队首元素
q.pop();
for(i=0;i<6;i++) //广度优先搜索
{
next.x=cur.x+dir[i][0];
next.y=cur.y+dir[i][1];
next.z=cur.z+dir[i][2];
if(next.x==a-1 && next.y==b-1 && next.z==c-1) //下一步就是目的地
{
ans=cur.steps+1;
while(!q.empty())
q.pop();
return ;
}
if(next.x>=0&&next.x<a&&next.y>=0&&next.y<b&&next.z>=0&&next.z<c)
if(map[next.x][next.y][next.z]!=1)
{
map[next.x][next.y][next.z]=1;
next.steps=cur.steps+1;
q.push(next);
}
}
}
ans=-1;
}
int main()
{
int i,j,k,step;
scanf("%d\n",&n);
while(n--)
{
scanf("%d %d %d %d",&a,&b,&c,&t);
for(i=0;i<a;i++)
for(j=0;j<b;j++)
for(k=0;k<c;k++)
scanf("%d",&map[i][j][k]);
if(a+b+c-3>t) {printf("-1\n");continue;}
if(map[a-1][b-1][c-1]==1) {printf("-1\n");continue;}
if(a==1&&b==1&&c==1){printf("-1\n");continue;}//考虑起点和终点相同的情况
start.x=0;
start.y=0;
start.z=0;
start.steps=0;
bfs();
if(ans>=0&&ans<=t)
printf("%d\n",ans);
else
printf("-1\n");
}
return 0;
}原文地址:http://blog.csdn.net/jiangx1994/article/details/38150083