poj 2251

http://poj.org/problem?id=2251

一道简单的BFS,只不过是二维数组,变三维数组,也就在原来基础上加了两个方向。

题意就是从S走到E,#不能走。

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <queue>
 4 #include <iostream>
 5 using namespace std;
 6 
 7 #define judge(x,y,z) mark[x][y][z]&&str1[x][y][z]!='#'&&x>=0&&x<l&&y>=0&&y<r&&z>=0&&z<c       //判断这个点是否可以走。
 8 char str1[31][31][31];
 9 int l,r,c,sx,sy,sz,ex,ey,ez,step[31][31][31];
10 int dic[6][3]{0,0,1,0,0,-1,1,0,0,-1,0,0,0,1,0,0,-1,0};    //方向。
11 
12 struct note{
13     int x,y,z;
14 };
15 bool mark[31][31][31];
16 queue<note>s;     //定义了一个s的结构体队列。因为一个点要通过三个值来确定,所以这里选择用结构体是比较方便的。
17 
18 void bfs(int x,int y,int z)
19 {
20     note u;
21     u.x=x,u.y=y,u.z=z;
22     while(!s.empty())
23         s.pop();
24     s.push(u);
25     while(!s.empty())
26     {
27         note v;
28         v=s.front();
29         s.pop();
30         if(v.x==ex&&v.y==ey&&v.z==ez) return;
31         for(int i=0;i<6;i++)
32         {
33             u.x=v.x+dic[i][0];
34             u.y=v.y+dic[i][1];
35             u.z=v.z+dic[i][2];
36             if(judge(u.x,u.y,u.z)){
37                 step[u.x][u.y][u.z]=step[v.x][v.y][v.z]+1;
38                 mark[u.x][u.y][u.z]=false;
39                 s.push(u);
40             }
41         }
42     }
43 }
44 
45 int main()
46 {
47     while(scanf("%d%d%d",&l,&r,&c),l!=0&&r!=0&&c!=0)
48     {
49         memset(mark,true,sizeof(mark));
50         memset(str1,0,sizeof(str1));
51         memset(step,0,sizeof(step));
52         for(int i=0;i<l;i++)
53             for(int j=0;j<r;j++)
54             {
55                 scanf("%s",str1[i][j]);
56                 for(int k=0;k<c;k++)
57                 {
58                     if(str1[i][j][k]=='S')
59                     {
60                             sx=i;
61                             sy=j;
62                             sz=k;
63                     }
64                     if(str1[i][j][k]=='E')
65                     {
66                         ex=i;
67                         ey=j;
68                         ez=k;
69                     }
70                 }
71             }
72         step[sx][sy][sz]=0;
73         bfs(sx,sy,sz);
74         if(step[ex][ey][ez]==0) printf("Trapped!
");       //如果走不到那个点,那么那个点的步数肯定是为0的,通过这个条件来判断是否可以找到那一个出口。
75         else printf("Escaped in %d minute(s).
",step[ex][ey][ez]);
76     }
77 }
原文地址:https://www.cnblogs.com/Tree-dream/p/5523991.html