HDU 1253 三维搜索bfs

也是以前做的一个题,当时不会。

bfs:

 1 #include<stdio.h>
 2 #include<string.h>
 3 int a,b,c;
 4 int vis[55][55][55],map[55][55][55];
 5 
 6 int dx[6]={0,0,0,0,-1,1};
 7 int dy[6]={0,0,1,-1,0,0};
 8 int dz[6]={1,-1,0,0,0,0};
 9 struct node
10 {
11     int x,y,z;
12     int time1;
13 }pos,npos,queue[55*55*55];
14 
15 int bfs()
16 {
17      int front=0,rear=0,d;
18      pos.x=0; pos.y=0; pos.z=0; pos.time1=0;
19      vis[0][0][0]=1;
20      queue[rear++]=pos;
21 
22      while(rear>front)
23      {
24          pos=queue[front++];
25          if(pos.x==a-1&&pos.y==b-1&&pos.z==c-1)
26          return pos.time1;
27 
28         for(d=0; d<6; d++)
29         {
30             npos.x=pos.x+dx[d]; npos.y=pos.y+dy[d]; npos.z=pos.z+dz[d]; npos.time1=pos.time1+1;
31             if(npos.x>=0&&npos.x<a&&npos.y>=0&&npos.y<b&&npos.z>=0&&npos.z<c
32                &&!vis[npos.x][npos.y][npos.z]&&!map[npos.x][npos.y][npos.z])
33             {
34                 vis[npos.x][npos.y][npos.z]=1;
35                 queue[rear++]=npos;
36             }
37         }
38      }
39      return -1;
40 };
41 
42 int main()
43 {
44     int t,i,j,k,time2,time;
45     scanf("%d",&t);
46     while(t--)
47     {
48         memset(vis,0,sizeof(vis));
49         scanf("%d%d%d%d",&a,&b,&c,&time2);
50         for(k=0; k<a; k++)
51         for(i=0; i<b; i++)
52         for(j=0; j<c; j++)
53         scanf("%d",&map[k][i][j]);
54         time=bfs();
55 
56         if(time<=time2&&time!=-1)
57         printf("%d\n",time);
58         else
59         printf("-1\n");
60     }
61 }
View Code

 

 

 

posted @ 2013-05-23 08:41  水门  阅读(130)  评论(0编辑  收藏  举报