HDU1242 Rescue 简单bfs

求最小步数

 1 #include<iostream>  
 2 #include<cstdio>  
 3 #include<cstring>  
 4 #include<cstdlib>  
 5 #include<queue>  
 6 using namespace std;
 7 char map[211][211];
 8 struct node
 9 {
10     int x,y,step;
11     friend bool operator<(node a,node b)
12     {
13         return a.step>b.step;    
14     }   
15 }cur,next;
16 int ex,ey,sx,sy;
17 int n,m;
18 
19 int bfs(void)
20 {
21     priority_queue<node>q;
22     cur.x=sx;
23     cur.y=sy;
24     cur.step=0;
25     q.push(cur);
26     while(!q.empty())
27     {
28         cur=q.top();
29         q.pop();
30         if(cur.x==ex&&cur.y==ey) return 1;
31         if(cur.x-1>=0&&map[cur.x-1][cur.y]!='#')
32         {
33             next=cur;
34             next.x--;
35             next.step++;
36             if(map[next.x][next.y]=='x') next.step++;
37             q.push(next);
38             map[next.x][next.y]='#';                                      
39         }
40         if(cur.y-1>=0&&map[cur.x][cur.y-1]!='#')
41         {
42             next=cur;
43             next.y--;
44             next.step++;
45             if(map[next.x][next.y]=='x') next.step++;
46             q.push(next);
47             map[next.x][next.y]='#';                                      
48         }
49         if(cur.x+1<n&&map[cur.x+1][cur.y]!='#')
50         {
51             next=cur;
52             next.x++;
53             next.step++;
54             if(map[next.x][next.y]=='x') next.step++;
55             q.push(next);
56             map[next.x][next.y]='#';                                      
57         }
58         if(cur.y+1<m&&map[cur.x][cur.y+1]!='#')
59         {
60             next=cur;
61             next.y++;
62             next.step++;
63             if(map[next.x][next.y]=='x') next.step++;
64             q.push(next);
65             map[next.x][next.y]='#';                                      
66         }               
67     }
68     return 0;
69 }
70 int main()
71 {
72     while(scanf("%d %d",&n,&m)!=EOF)
73     {
74         for(int i=0;i<n;i++)
75         {
76             scanf("%s",&map[i]); 
77             for(int j=0;j<m;j++)
78             {
79                 if(map[i][j]=='r') 
80                 {
81                     sx=i;
82                     sy=j;
83                 }    
84                 if(map[i][j]=='a')
85                 {
86                     ex=i;
87                     ey=j;                  
88                 }    
89             }
90         }
91         if(bfs()) printf("%d\n",cur.step);
92         else printf("Poor ANGEL has to stay in the prison all his life.\n");               
93     }       
94 } 

 

posted on 2014-04-25 10:52  >_<  阅读(141)  评论(0编辑  收藏  举报

导航