首页 > 代码库 > 【HDOJ】2612 Find a way

【HDOJ】2612 Find a way

BFS。

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <queue>
 5 using namespace std;
 6 
 7 #define INF 0x3fffffff
 8 
 9 typedef struct node_st {
10     int x, y, s;
11     node_st() {}
12     node_st(int xx, int yy, int ss) {
13         x = xx; y = yy; s = ss;
14     }
15 } node_st;
16 
17 char visit[205][205];
18 char map[205][205];
19 int step[2][205][205];
20 int n, m;
21 int direct[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};
22 
23 void bfs(int x, int y, int sel) {
24     int i, s;
25     queue<node_st> que;
26     node_st node;
27 
28     memset(visit, 0, sizeof(visit));
29     memset(step[sel], 0, sizeof(step[sel]));
30     visit[x][y] = 1;
31     que.push(node_st(x,y,0));
32 
33     while ( !que.empty() ) {
34         node = que.front();
35         que.pop();
36         s = node.s + 1;
37         for (i=0; i<4; ++i) {
38             x = node.x + direct[i][0];
39             y = node.y + direct[i][1];
40             if (x<0 || x>=n || y<0 || y>=m)
41                 continue;
42             if (visit[x][y])
43                 continue;
44             visit[x][y] = 1;
45             if (map[x][y] == #)
46                 continue;
47             if (map[x][y] == @)
48                 step[sel][x][y] = s;
49             que.push(node_st(x,y,s));
50         }
51     }
52 }
53 
54 int main() {
55     int i, j, tmp, min;
56     int yx, yy, mx, my;
57 
58     while (scanf("%d %d%*c", &n, &m) != EOF) {
59         for (i=0; i<n; ++i) {
60             scanf("%s", map[i]);
61             for (j=0; j<m; ++j) {
62                 if (map[i][j] == Y) {
63                     yx = i;
64                     yy = j;
65                 } else if (map[i][j] == M) {
66                     mx = i;
67                     my = j;
68                 }
69             }
70         }
71         bfs(yx, yy, 0);
72         bfs(mx, my, 1);
73         min = INF;
74         for (i=0; i<n; ++i) {
75             for (j=0; j<m; ++j) {
76                 if (step[0][i][j] && step[1][i][j]) {
77                     tmp = step[0][i][j] + step[1][i][j];
78                     if (tmp < min)
79                         min = tmp;
80                 }
81             }
82         }
83         printf("%d\n", min*11);
84     }
85 
86     return 0;
87 }