Rescue--hdu1242

题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=1242

运用优先队列进行广搜

 1 #include <stdio.h>
 2 #include<iostream>
 3 #include <string.h>
 4 #include <queue>
 5 #include <algorithm>
 6 #define inf 0x6ffffff
 7 #define N 220
 8 using namespace std;
 9 
10 int n,m,vis[N][N];
11 int dir[4][2]={ {0,1},{0,-1},{1,0},{-1,0} };
12 char maps[N][N];
13 
14 struct node
15 {
16     int x,y,step;
17     friend bool operator < (node a,node b)
18     {
19         return a.step > b.step;
20     }
21 };
22 bool judge(int x,int y)
23 {
24     return x<n&&x>=0&&y>=0&&y<m&&vis[x][y]==0&&maps[x][y]!='#';
25 }
26 int bfs(node s,node e)
27 {
28     memset(vis,0,sizeof(vis));
29     node q;
30     priority_queue<node> Q;
31     Q.push(s);
32     vis[s.x][s.y]=1;
33     while(!Q.empty())
34     {
35         q=Q.top();
36         Q.pop();
37         if(q.x==e.x&&q.y==e.y)
38             return q.step;
39 
40         for(int i=0;i<4;i++)
41         {
42             s.x=q.x+dir[i][0];
43             s.y=q.y+dir[i][1];
44             if(judge(s.x,s.y))
45             {
46                 if(maps[s.x][s.y]=='x')
47                     s.step=q.step+2;
48                 else
49                     s.step=q.step+1;
50                 vis[s.x][s.y]=1;
51                 Q.push(s);
52             }
53         }
54     }
55     return -1;
56 }
57 
58 int main()
59 {
60     int i,j,ans;
61     node s,e;
62     while(scanf("%d%d",&n,&m)!=EOF)
63     {
64         memset(maps,0,sizeof(maps));
65         for(i=0;i<n;i++)
66         {
67             for(j=0;j<m;j++)
68             {
69                 cin>>maps[i][j];
70                 if(maps[i][j]=='a')
71                     s.x=i,s.y=j;
72                 if(maps[i][j]=='r')
73                     e.x=i,e.y=j;
74             }
75         }
76         s.step=0;
77 
78         ans=bfs(s,e);
79 
80         if(ans==-1)
81             printf("Poor ANGEL has to stay in the prison all his life.
");
82         else
83             printf("%d
",ans);
84     }
85     return 0;
86 }
原文地址:https://www.cnblogs.com/zhengguiping--9876/p/4429016.html