hdu 1242 Rescue BFS+优先队列

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1242

题意:"r"是起点,"a"是终点,'.'是路,'x'是守卫,'#'是不能走的地方。杀掉守卫要多花1个单位时间,每次上下左右移动要花一个单位时间。问到终点花的最少时间。

思路:这种N*M的地图且带权(一个是1,一个是2)的一般使用BFS+优先队列,如果不带权可以直接使用BFS。

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 int N, M;
 4 #define maxn 210
 5 #define inf 0x3f3f3f3f
 6 char mp[maxn][maxn];
 7 int sx, sy, ex, ey;
 8 int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
 9 struct Node
10 {
11     int x, y, d;
12     Node(int xx, int yy, int dd)
13     {
14         x = xx; y = yy; d = dd;
15     }
16     Node(){}
17     friend bool operator <(Node a, Node b)
18     {
19         return a.d > b.d;
20     }
21 };
22 int dist[maxn][maxn];
23 int bfs()
24 {
25     memset(dist, inf, sizeof(dist));
26     priority_queue <Node> q;
27     dist[sx][sy] = 0;
28     q.push(Node(sx, sy, 0));
29     while(!q.empty())
30     {
31         Node u = q.top(); q.pop();
32         for(int i = 0; i < 4; i++)
33         {
34             int xx = u.x + dir[i][0];
35             int yy = u.y + dir[i][1];
36            //cout<<xx<<" "<<yy<<endl;
37             if(xx < 0 || xx >= N || yy < 0 || yy >= M || mp[xx][yy] == '#') continue;
38             if(mp[xx][yy] == 'a') return u.d+1;
39             
40             Node temp = Node(xx, yy, u.d);
41             temp.d++;
42             if(mp[xx][yy] == 'x') temp.d++;
43             if(dist[xx][yy] >= temp.d) 
44             {
45                 q.push(temp);
46                 dist[xx][yy] = temp.d;
47             }
48         }
49     }
50     return -1;
51     
52 }
53 int main() 
54 {
55     //freopen("in.txt", "r", stdin);
56     //freopen("out.txt", "w", stdout);
57     while(~scanf("%d%d", &N, &M))
58     {
59         for(int i = 0; i < N; i++)
60         {
61             scanf("%s", mp[i]);
62         }
63         for(int i = 0; i < N; i++)
64         {
65             for(int j = 0; j < M; j++)
66             {
67                 if(mp[i][j] == 'r'){sx = i; sy = j;}
68                 if(mp[i][j] == 'a'){ex = i; ey = j;}
69             }
70         }
71         int ans = bfs();
72         if(ans == -1) printf("Poor ANGEL has to stay in the prison all his life.\n");
73         else printf("%d\n", ans);
74     }
75     return 0;
76 }

 

posted @ 2016-04-06 14:04  下周LGD该赢了吧  阅读(136)  评论(0编辑  收藏  举报