【HDOJ】1180 诡异的楼梯

bfs+优先队列。wa了N次,才发现可以停留等待楼梯变换方向。

 1 #include <iostream>
 2 #include <queue>
 3 #include <cstdio>
 4 #include <cstring>
 5 using namespace std;
 6 
 7 #define MAXNUM 55
 8 
 9 typedef struct node_st {
10     int x, y, t;
11     node_st() {}
12     node_st(int xx, int yy, int tt) {
13         x = xx; y = yy; t = tt;
14     }
15     friend bool operator < (node_st a, node_st b) {
16         return a.t > b.t;
17     }
18 } node_st;
19 
20 char map[MAXNUM][MAXNUM];
21 char visit[MAXNUM][MAXNUM];
22 int n, m;
23 int begx, begy, endx, endy;
24 int direct[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
25 
26 int bfs(int begx, int begy) {
27     priority_queue<node_st> que;
28     node_st node;
29     int i, x, y, nx, ny, t;
30 
31     que.push(node_st(begx, begy, 0));
32     memset(visit, 0, sizeof(visit));
33     visit[begx][begy] = 1;
34 
35     while ( !que.empty() ) {
36         node = que.top();
37         if (map[node.x][node.y] == 'T') {
38             return node.t;
39         }
40         que.pop();
41         for (i=0; i<4; ++i) {                
42             x = node.x + direct[i][0];
43             y = node.y + direct[i][1];
44             if (x<0 || x>=n || y<0 || y>=m)
45                 continue;
46             if (visit[x][y] || map[x][y] == '*')
47                 continue;
48             if (map[x][y] == '.' || map[x][y]=='T') {
49                 que.push(node_st(x,y,node.t+1));
50                 visit[x][y] = 1;
51                 continue;
52             }
53             if (map[x][y]=='|' || map[x][y]=='-') {
54                 nx = x + direct[i][0];
55                 ny = y + direct[i][1];
56                 t = node.t + 1;
57                 if (nx<0 || nx>=n || ny<0 || ny>=m)
58                     continue;
59                 if (visit[nx][ny] || map[nx][ny]=='*')
60                     continue;
61                 if ( ((map[x][y]=='|') && ((node.t&1)==0) && (i==2||i==3)) ||
62                      ((map[x][y]=='|') && ((node.t&1)!=0) && (i==0||i==1)) ||
63                      ((map[x][y]=='-') && ((node.t&1)==0) && (i==0||i==1)) ||
64                      ((map[x][y]=='-') && ((node.t&1)!=0) && (i==2||i==3)) )
65                      ++t;
66                 visit[nx][ny] = 1;
67                 que.push(node_st(nx, ny, t));
68             }
69         }
70     }
71 
72     return -1;
73 }
74 
75 int main() {
76     int i, j;
77 
78     while (scanf("%d %d%*c",&n,&m) != EOF) {
79         for (i=0; i<n; ++i) {
80             scanf("%s", map[i]);
81             for (j=0; j<m; ++j) {
82                 if (map[i][j] == 'S') {
83                     begx = i;
84                     begy = j;
85                 }
86             }
87         }
88         i = bfs(begx, begy);
89         printf("%d\n", i);
90     }
91 
92     return 0;
93 }

 

posted on 2014-05-29 18:03  Bombe  阅读(268)  评论(0编辑  收藏  举报

导航