称不上算法的算法-3.bfs

HRBUST1613

待优化

注意换行对于char读取的影响!!!

bfs大体步骤:建立记录地图,确定起点,起点入队,以队列不空为条件循化,在循环内不断把队列的首元素当成操作元素,并把此操作元素的所有下层可能结果入队。

这样循环往复就可以把每层搜尽。

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<queue>
 4 using namespace std;
 5 char map[110][110];
 6 struct point{
 7     int x;
 8     int y;
 9 };
10 int xmove[4]={0,0,-1,1};
11 int ymove[4]={1,-1,0,0};
12 int times[110][110];
13 point P[10000];
14 int main(void){
15     int t;
16     scanf("%d",&t);
17     for(int tt=0;tt<t;tt++){
18         point start;
19         int sumofp=0;
20         int judg=0;
21         memset(times,0,sizeof(times));
22         int R,C;
23         scanf("%d%d",&R,&C);
24         getchar();
25         for(int i=0;i<R;i++){
26             for(int j=0;j<C;j++){
27                 scanf("%c",&map[i][j]);
28                 if(map[i][j]=='Z'){
29                     start.x=i;
30                     start.y=j;
31                 }
32                 else if(map[i][j]=='P'){
33                     point tmp;
34                     tmp.x=i;
35                     tmp.y=j;
36                     P[sumofp]=tmp;
37                     sumofp++;
38                 }
39             }
40             getchar();
41         }
42         queue<point> que;
43         que.push(start);
44         while(!que.empty()){
45             point atmp=que.front();
46             que.pop();
47             for(int g=0;g<4;g++){
48                 point nowoption;
49                 nowoption.x=atmp.x+xmove[g];
50                 nowoption.y=atmp.y+ymove[g];
51                 if(nowoption.x>=0&& nowoption.x<R&& nowoption.y>=0&& nowoption.y<C&& map[nowoption.x][nowoption.y]!='#'&&times[nowoption.x][nowoption.y]==0){
52                     if(map[nowoption.x][nowoption.y]=='W'){
53                         judg=1;
54                         printf("%d\n",times[atmp.x][atmp.y]+1);
55                         break;
56                     }
57                     else if(map[nowoption.x][nowoption.y]=='.'){
58                         que.push(nowoption);
59                         times[nowoption.x][nowoption.y]=times[atmp.x][atmp.y]+1;
60                     }
61                     else if(map[nowoption.x][nowoption.y]=='P'){
62                         for(int j=0;j<sumofp;j++){
63                             que.push(P[j]);
64                             times[P[j].x][P[j].y]=times[atmp.x][atmp.y]+1;
65                         }
66                     }
67                 }
68             }
69             if(judg==1)
70                 break;
71         }
72         if(judg==0){
73             printf("IMPOSSIBLE\n");
74         }
75     }
76 }

猜你喜欢

转载自www.cnblogs.com/liuzey/p/8965206.html