简单的BFS
注意以下几点:
- *思路首先分析可走的路的总数是否大于等于最短路径数(最短路径数=a+b+c-2),如果小于怎样都无法到达出口
- *所以可以直接输出-1,还有总的时间数小于最短时间(最短时间数=a+b+c-2)也是无法到达出口,除去以上情况
- *然后使用BFS进行搜寻就可以了
- *如果想看代码论坛有我就不贴了
郁闷,做出来还是要1531ms
哎,代码能力还是不行
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
#include <iostream>
#include <queue>
using namespace std;
struct node
{
int x,y,z,t;
};
int map[51][51][51];
int a,b,c,t,s;
bool escape;
int dir[6][3] = {{1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1}};
void BFS(int x,int y,int z,int time)
{
queue<node> q;
node n,p;
n.x = x;
n.y = y;
n.z = z;
n.t = time;
q.push(n);
map[x][y][z] = 1;
while(!q.empty())
{
n = q.front();
q.pop();
if(n.x == a-1 && n.y == b-1 && n.z == c-1 && n.t <= t)
{
escape = true;
s = n.t;
break;
}
if(n.t > t)
break;
for(int i = 0;i < 6;i++)
{
int tx = n.x + dir[i][0];
int ty = n.y + dir[i][1];
int tz = n.z + dir[i][2];
if(tx < 0 || tx >= a || ty < 0 || ty >= b || tz < 0 || tz >= c)
continue;
if(map[tx][ty][tz] == 1)
continue;
p.x = tx;
p.y = ty;
p.z = tz;
p.t = n.t + 1;
if(p.t+a-1-p.x+b-1-p.y+c-1-p.z > t)
{
map[tx][ty][tz] = 1;
continue;
}
q.push(p);
map[tx][ty][tz] = 1;
}
}
}
int main()
{
//freopen("1.txt","r",stdin);
int k,i,j,x,wall;
scanf("%d",&k);
while(k--)
{
scanf("%d %d %d %d",&a,&b,&c,&t);
wall = 0;
for(i = 0;i < a;i++)
for(j = 0;j < b;j++)
for(x = 0;x < c;x++)
{
scanf("%d",&map[i][j][x]);
if(map[i][j][x])
wall++;
}
escape = false;
if((a*b*c - wall < a+b+c-2) || (t < a+b+c-3))
{
printf("-1\n");
continue;
}
BFS(0,0,0,0);
if(escape)
printf("%d\n",s);
else
printf("-1\n");
}
return 0;
}