HDU2612 Find a way

解题思路:简单的宽搜题,分别存储Y,M到每个@的距离,然后求出每个@处

     对应累加的最小值。见代码:、

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<algorithm>
 4 #include<queue>
 5 using namespace std;
 6 #define inf 0x3f3f3f3f
 7 const int maxn = 205;
 8 int vis[maxn][maxn], n, m, min1, dir[4][2] = {1, 0, -1, 0, 0, 1, 0, -1};
 9 int dis[maxn][maxn][2], flag;
10 char mapp[maxn][maxn];
11 
12 struct node{
13     int x, y;
14     int cnt;
15 }s, e;
16 
17 queue<node> q;
18 
19 void bfs(int x, int y)
20 {
21     memset(vis, 0, sizeof(vis)); //初始化
22     s.x = x, s.y = y, s.cnt = 0;
23     vis[x][y] = 1;
24     while(!q.empty()) q.pop();
25     q.push(s);
26 
27     while(!q.empty())
28     {
29         s = q.front(); q.pop();
30 
31         for(int i = 0; i < 4; i++)
32         {
33             e.x = s.x + dir[i][0];
34             e.y = s.y + dir[i][1];
35             e.cnt = s.cnt + 1;
36             if(mapp[e.x][e.y] == '#' || vis[e.x][e.y]) continue;
37             //存储下到每个@时对应的e.cnt的值
38             if(mapp[e.x][e.y] == '@') dis[e.x][e.y][flag] = e.cnt;
39            // dis[e.x][e.y][flag] = e.cnt;
40             vis[e.x][e.y] = 1;
41             q.push(e);
42         }
43     }
44 }
45 
46 int main()
47 {
48     while(~scanf("%d %d", &n, &m))
49     {
50         memset(mapp, '#', sizeof(mapp));
51         memset(vis, 0, sizeof(vis));
52 
53         //刚开是这步初始化,结果WA了一发,好好思考为什么
54         //memset(dis, 0, sizeof(dis));
55 
56         for(int i = 1; i <= n; i++)
57         for(int j = 1; j <= m; j++)
58         dis[i][j][0] = dis[i][j][1] = inf;
59 
60         for(int i = 1; i <= n; i++)
61         for(int j = 1; j <= m; j++) scanf(" %c", &mapp[i][j]);
62 
63         min1 = inf;
64         for(int i = 1; i <= n; i++)
65         for(int j = 1; j <= m; j++)
66         {
67             if(mapp[i][j] == 'Y')
68             {
69                 flag = 0; //将flag标记为0,表示Y到@
70                 bfs(i, j);
71             }
72 
73             if(mapp[i][j] == 'M')
74             {
75                 flag = 1;
76                 bfs(i, j);
77             }
78         }
79 
80         for(int i = 1; i <= n; i++)
81         for(int j = 1; j <= m; j++)
82         {
83             //求出到每个@对应最小的时间
84             if(mapp[i][j] == '@') min1 = min(min1, dis[i][j][0]+dis[i][j][1]);
85         }
86         printf("%d\n", min1 * 11); //结果*11即可
87     }
88     return 0;
89 }
View Code

 

posted on 2015-10-12 20:47  改写历史,倾尽天下  阅读(129)  评论(0编辑  收藏  举报

导航