HDU杭电 1253 胜利大逃亡(图 BFS)

本题难度并不大,一个普通的用BFS求解的题,值得注意的是数据的输入(三维数据输入被绕了几圈);还有就是最后的出口可以表示墙,无法出去(就是没考虑到这点WA了一次);剩下的就是BFS的常规思路及框架了。


  1. #include<cstdio>
  2. #include<vector>
  3. #include<queue>
  4. #include<cstring>
  5. using namespace std;
  6. const int len=50+10;
  7. int K,A,B,C,T;
  8. struct node{
  9.     int x,y,z;
  10.     node(int x1=0,int y1=0,int z1=0):x(x1),y(y1),z(z1){}
  11. };
  12. int d[len][len][len];                             //从初始位置到当前位置的长度
  13. int p[len][len][len];                             //输入数据的保存
  14. node n0,nt;                                          //初始位置和最终位置
  15. void read(){
  16.     scanf("%d%d%d%d",&A,&B,&C,&T);
  17.     n0.x=0,n0.y=0,n0.z=B-1;
  18.     nt.x=A-1,nt.y=C-1,nt.z=0;
  19.     for(int x=0;x<A;x++)
  20.         for(int z=B-1;z>=0;z--)
  21.             for(int y=0;y<C;y++)
  22.                 scanf("%d",&p[x][y][z]);
  23. }
  24. const int dir[][3]={{0,0,1},{0,0,-1},{0,-1,0},{0,1,0},{1,0,0},{-1,0,0}}; //上下左右前后 
  25. void print(const node &u){
  26.     if(d[u.x][u.y][u.z]<=T)
  27.     printf("%d\n",d[u.x][u.y][u.z]);
  28.     else printf("-1\n");
  29. }
  30. bool isValid(const node &v){
  31.     return v.x>=0 && v.x<A && v.y>=0 && v.y<C && v.z>=0 && v.z<B;
  32. }
  33. void bfs(){
  34.     queue<node>q;
  35.     q.push(n0);
  36.     memset(d,0,sizeof(d));

  37.     while(!q.empty()){
  38.         node u=q.front();q.pop();
  39.         if(u.x== nt.x && u.y== nt.y && u.z == nt.z){
  40.             print(u);
  41.             return ;
  42.         } 
  43.         for(int i=0;i<6;i++){
  44.             node v=node(u.x+dir[i][0],u.y+dir[i][1],u.z+dir[i][2]);
  45.             if(d[v.x][v.y][v.z]==0 && isValid(v) && !p[v.x][v.y][v.z]){         //p[][][]=1时表示墙,不能放入队列中 
  46.                 d[v.x][v.y][v.z]=d[u.x][u.y][u.z]+1;
  47.                 q.push(v);
  48.             }
  49.         }
  50.     }
  51.     printf("-1\n");           //这里值得注意,出口可以表示墙,此时无法出去,通过这条语句输出结果。
  52. }
  53. int main(){
  54.     scanf("%d",&K);
  55.     while(K--){
  56.         read();
  57.         bfs();
  58.     }
  59.     return 0;
  60. }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柏油

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值