BFS(1)-胜利大逃亡

来源:互联网 发布:windows安装redis步骤 编辑:程序博客网 时间:2024/05/29 15:09

题目描述: 
Ignatius被魔王抓走了,有一天魔王出差去了,这可是Ignatius逃亡的好机会.魔王住在一个城堡里,城堡是一个A*B*C的立方体,可以被表示成A个B*C的矩阵,刚开始Ignatius被关在(0,0,0)的位置,离开城堡的门在(A-1,B-1,C-1)的位置,现在知道魔王将在T分钟后回到城堡,Ignatius每分钟能从一个坐标走到相邻的六个坐标中的其中一个.现在给你城堡的地图,请你计算出Ignatius能否在魔王回来前离开城堡(只要走到出口就算离开城堡,如果走到出口的时候魔王刚好回来也算逃亡成功),如果可以请输出需要多少分钟才能离开,如果不能则输出-1. 
输入: 
输入数据的第一行是一个正整数K,表明测试数据的数量.每组测试数据的第一行是四个正整数A,B,C和T(1<=A,B,C<=50,1<=T<=1000),它们分别代表城堡的大小和魔王回来的时间.然后是A块输入数据(先是第0块,然后是第1块,第2块……),每块输入数据有B行,每行有C个正整数,代表迷宫的布局,其中0代表路,1代表墙。 
输出: 
对于每组测试数据,如果Ignatius能够在魔王回来前离开城堡,那么请输出他最少需要多少分钟,否则输出-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


这是一道BFS题,求得是最少耗时(最优化求解),BFS时求解树的深度与用时成线性关系,即先访问到的结点用时一定不小于后访问到的节点。由于图中可能出现环路,之前访问过的节点在以后可能还会访问到,所以用mark[][][]来标记某个节点是否访问过,如果访问过则不再访问它,通过这样来剪枝,使求解树的规模大大降低。

#include <stdio.h>  #include<stdlib.h>#include <queue>  using namespace std;    struct N{       //状态结构体,用于保存立方的信息    int x,y,z;      int t;  };    queue<N> Q;                 int maze[50][50][50];   //保存立方体,是0还是1,判断是否为墙 bool mark[50][50][50];  //标记已访问  int go[6][3] = {1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1};    //方向数组。每步只能向6个方向走    int BFS(int a , int b , int c,int T)  {      while(!Q.empty()){          N tmp = Q.front();if(tmp.t>T) //先判断,减少多余操作return -1;        Q.pop();          for(int i = 0 ; i < 6 ; ++i){  //每次能走动的可能            int nowx = tmp.x + go[i][0];              int nowy = tmp.y + go[i][1];              int nowz = tmp.z + go[i][2];              int nowt = tmp.t + 1;              if(nowx < 0 || nowx >= a || nowy < 0 || nowy >= b || nowz < 0 || nowz >= c)                  continue;              if(maze[nowx][nowy][nowz] == 1) continue;  //判断            if(mark[nowx][nowy][nowz] == true) continue;                              N newp;              newp.x = nowx; newp.y = nowy ; newp.z = nowz;  //入队列            newp.t = nowt;              mark[nowx][nowy][nowz] = true;              Q.push(newp);              if(nowx == a-1 && nowy == b-1 && nowz == c-1){                  return newp.t;              }          }      }      return -1;  //若所以状态检查完毕,找不到坐标,死定了-1}    int main()  {      int K;      scanf("%d",&K);      while(K--){          int a,b,c,T;          scanf("%d%d%d%d",&a,&b,&c,&T);          for(int i = 0 ; i < a ; ++i){              for(int j = 0 ; j < b ; ++j){                  for(int k = 0 ; k < c ; ++k){                      scanf("%d",&maze[i][j][k]);                      mark[i][j][k] = false;                  }              }          }            while(!Q.empty()) Q.pop();          mark[0][0][0] = true;          N tmp;          tmp.x = 0;          tmp.y = 0;          tmp.z = 0;          tmp.t = 0;          Q.push(tmp);            int ans = BFS(a,b,c,T);  //把时间也传递过去用于判断        if(ans <= T) printf("%d\n",ans);  //go home        else printf("-1\n");  //die    }  system("pause");    return 0;  }


0 0