hdu 1180 优先队列 + bfs

题目链接:

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

 1 //优先队列 + bfs
 2 //wrong1 楼梯是每分钟变化一次 wrong2 奇偶性判断错误
 3 #include <iostream>
 4 #include <cstring>
 5 #include <queue>
 6 #include <cstdio>
 7 using namespace std;
 8 int n, m, sx, sy, dir[4][2] = {{1,0}, {-1,0}, {0,-1}, {0,1}};
 9 char map[25][25]; bool visit[25][25];
10 
11 bool OK(int x, int y){
12     if(x > 0 && y > 0 && x <= n && y <= m && !visit[x][y] && map[x][y] != '*'return true;
13     return false;
14 }
15 
16 struct node{
17     int x, y, step;
18     bool operator < (const node& n) const{
19         return step > n.step;
20     }
21 };
22 
23 void bfs(){
24     priority_queue<node> q; node n1, n2, n3;
25     n1.x = sx; n1.y = sy; n1.step = 0; q.push(n1);
26     while(!q.empty()){
27         n1 = q.top(); q.pop();
28         if(map[n1.x][n1.y] == 'T'){ cout<<n1.step<<endl; break;}
29         for(int i = 0; i < 4; ++i){
30             n2.x = n1.x + dir[i][0]; n2.y = n1.y + dir[i][1]; n2.step = n1.step + 1;
31             if(!OK(n2.x, n2.y)) continue;
32             if(map[n2.x][n2.y] == '|' || map[n2.x][n2.y] == '-'){
33                 n3.x = n2.x + dir[i][0]; n3.y = n2.y + dir[i][1]; n3.step = n2.step;
34                 if(!OK(n3.x, n3.y)) continue;//根据奇偶性判断是否需要等到下一分才能过楼梯
35                 if((map[n2.x][n2.y] == '|' && (n1.step & 1) && i < 2) ||
36                    (map[n2.x][n2.y] == '|' && !(n1.step & 1) && i > 1) ||
37                    (map[n2.x][n2.y] == '-' && !(n1.step & 1) && i < 2) ||
38                    (map[n2.x][n2.y] == '-' && (n1.step & 1) && i > 1))
39                    n3.step++;
40                 visit[n3.x][n3.y] = true;
41                 q.push(n3); continue;
42             }
43             visit[n2.x][n2.y] = true; q.push(n2);
44         }
45     }
46 }
47 
48 int main()
49 {
50     //freopen("in.txt", "r", stdin);
51     while(cin>>n>>m){
52         for(int i = 1; i <= n; ++i){
53             cin>>(map[i]+1);
54             for(int j = 1; j <= m; ++j)
55             if(map[i][j] == 'S') sx = i, sy = j;
56         }
57         memset(visit, falsesizeof(visit));
58         visit[sx][sy] = true;
59         bfs();
60     }
61     return 0;
62 }
View Code

 

posted @ 2013-08-06 15:50  YaLing  阅读(153)  评论(0编辑  收藏  举报