您的位置:首页 > 其它

hdu 1253:胜利大逃亡(基础广搜BFS)

2014-03-28 09:59 477 查看

胜利大逃亡

Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 23779 Accepted Submission(s): 9125


[align=left]Problem Description[/align]
Ignatius被魔王抓走了,有一天魔王出差去了,这可是Ignatius逃亡的好机会.

魔王住在一个城堡里,城堡是一个A*B*C的立方体,可以被表示成A个B*C的矩阵,刚开始Ignatius被关在(0,0,0)的位置,离开城堡的门在(A-1,B-1,C-1)的位置,现在知道魔王将在T分钟后回到城堡,Ignatius每分钟能从一个坐标走到相邻的六个坐标中的其中一个.现在给你城堡的地图,请你计算出Ignatius能否在魔王回来前离开城堡(只要走到出口就算离开城堡,如果走到出口的时候魔王刚好回来也算逃亡成功),如果可以请输出需要多少分钟才能离开,如果不能则输出-1.



[align=left]Input[/align]
输入数据的第一行是一个正整数K,表明测试数据的数量.每组测试数据的第一行是四个正整数A,B,C和T(1<=A,B,C<=50,1<=T<=1000),它们分别代表城堡的大小和魔王回来的时间.然后是A块输入数据(先是第0块,然后是第1块,第2块......),每块输入数据有B行,每行有C个正整数,代表迷宫的布局,其中0代表路,1代表墙.(如果对输入描述不清楚,可以参考Sample Input中的迷宫描述,它表示的就是上图中的迷宫)

特别注意:本题的测试数据非常大,请使用scanf输入,我不能保证使用cin能不超时.在本OJ上请使用Visual C++提交.

[align=left]Output[/align]
对于每组测试数据,如果Ignatius能够在魔王回来前离开城堡,那么请输出他最少需要多少分钟,否则输出-1.

[align=left]Sample Input[/align]

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

[align=left]Sample Output[/align]

11

[align=left]Author[/align]
Ignatius.L

[align=left]Recommend[/align]
Ignatius.L | We have carefully selected several similar problems for you: 1372 1242 1072 1240 1312

  BFS广搜基础题。
  这道题挺有新意,把二维地图的搜索转变成了三维地图的搜索,不过换汤不换药,思路是一样的。直接拿过来BFS的模板,改动了一下,提交就过了。但是效率不高,1000+MS,有大神路过希望贴个更快的代码,感激不尽!^_^
  参考代码

#include <iostream>
#include <string.h>
#include <queue>
using namespace std;
int a[55][55][55];    //记录地图
int isv[55][55][55];    //记录访问过没有
int dx[6] = {0,1,0,-1,0,0};
int dy[6] = {1,0,-1,0,0,0};
int dz[6] = {0,0,0,0,-1,1};
int A,B,C,T;
struct NODE{
int x;
int y;
int z;
int step;
};
bool judge(int x,int y,int z,int step)
{
if( x<1 || y<1 || z<1 || x>A || y>B || z>C )    //出界
return 1;
if( isv[x][y][z] )    //走过
return 1;
if( a[x][y][z]==1 )    //遇到墙
return 1;
if(step+1>T)    //如果走这一步超过了时间,不能走
return 1;
return 0;
}
int bfs(int x,int y,int z)    //返回到达终点的时间
{
memset(isv,0,sizeof(isv));
queue <NODE> q;
NODE cur,next;
cur.x = x;
cur.y = y;
cur.z = z;
cur.step = 0;
isv[1][1][1] = true;
q.push(cur);    //第一个节点入队
while(!q.empty()){
cur = q.front();
q.pop();    //队首出队
if( cur.x==A && cur.y==B && cur.z==C){
return cur.step;
}
for(int i=0;i<6;i++){
int nx = cur.x + dx[i];
int ny = cur.y + dy[i];
int nz = cur.z + dz[i];
if(judge(nx,ny,nz,cur.step))    //判定
continue;
//可以走
next.x = nx;
next.y = ny;
next.z = nz;
isv[nx][ny][nz] = true;    //记录访问过
next.step = cur.step + 1;
q.push(next);
}
}
return 0;
}
int main()
{
int n;
cin>>n;
while(n--){
scanf("%d%d%d%d",&A,&B,&C,&T);
int i,j,k;
for(i=1;i<=A;i++)
for(j=1;j<=B;j++)
for(k=1;k<=C;k++)
scanf("%d",&a[i][j][k]);
int step = bfs(1,1,1);
if(step)    //到达终点
printf("%d\n",step);
else
printf("-1\n");
}
return 0;
}


Run IDSubmit TimeJudge StatusPro.IDExe.TimeExe.MemoryCode Len.LanguageAuthor
104167452014-03-28 09:53:41Accepted12531140MS1652K1877 BC++freecode
Freecode : www.cnblogs.com/yym2013
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: