POJ 2251宽搜、

因为这个题做了两次犯了两次不同的错误、

第一次用的dfs死活都超时

第二次把定义队列定义在了全局变量的位置,导致连WA了几次、最后找到原因的我真的想一巴掌拍死自己

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<queue>
 4 using namespace std;
 5 const int qq=40;
 6 int vis[qq][qq][qq];
 7 char map[qq][qq][qq];
 8 int tz,ty,tx,k,n,m,sx,sy,sz;
 9 int dir[6][3]={-1,0,0,1,0,0,0,-1,0,0,1,0,0,0,1,0,0,-1};
10 struct point{
11     int a,b,c;
12     int step;
13 };
14 int check(int z,int y,int x)
15 {
16     if(z<0||y<0||x<0||z>=k||y>=n||x>=m||vis[z][y][x]||map[z][y][x]=='#')
17         return 0;
18     return 1;
19 }
20 void bfs()
21 {    
22     queue<point>Q;                    //就是这个定义队列放在了bfs函数外、导致我WA了很多次特地来提醒自己 
23     memset(vis,0,sizeof(vis));        //在写宽搜的时候一定不要犯同样的错误了、 
24     point now,ans;
25     now.step=0;now.a=sz;now.b=sy;now.c=sx;
26     vis[sz][sy][sx]=1;
27     Q.push(now);
28     while(!Q.empty()){
29         ans=Q.front();
30         Q.pop();
31         if(ans.a==tz&&ans.b==ty&&ans.c==tx){
32             printf("Escaped in %d minute(s).
",ans.step);
33             return;
34         }
35         for(int i=0;i<6;++i){
36             now.a=ans.a+dir[i][0];
37             now.b=ans.b+dir[i][1];
38             now.c=ans.c+dir[i][2];
39             if (check(now.a,now.b,now.c))
40             {
41                 now.step=ans.step+1;
42                 vis[now.a][now.b][now.c]=1;
43                 Q.push(now);
44             }
45         }
46     }
47     printf("Trapped!
");
48     return;
49 }
50 int main()
51 {    
52     while(~scanf("%d %d %d%*c",&k,&n,&m)&&k)
53     {        
54         for(int i,j,l=0;l<k;++l){
55             for(j=0;j<n;++j){
56                 for(i=0;i<m;++i){
57                     map[l][j][i]=getchar();
58                     if (map[l][j][i]=='S'){
59                         sx=i;sy=j;sz=l;
60                     }
61                     else if (map[l][j][i]=='E'){
62                         tx=i;ty=j;tz=l;
63                     }
64                 }
65                 getchar();
66             }
67             getchar();
68         }
69         bfs();
70     }
71     return 0;
72 }

做搜索题目一定要思路清晰、然后是代码的意义要明白的透彻

原文地址:https://www.cnblogs.com/sasuke-/p/5184158.html