题目:http://acm.hdu.edu.cn/showproblem.php?pid=2612
Y,M分别是两个人的位置,#表示障碍物,. 表示可以通过,@表示KFC的位置,现Y,M要到一家KFC见面,要找到一家KFC使两人所花的总时间最少,输出最少时间。
(每走一步花费11分钟)
分别以Y和M为起点,计算出他们到达每一家KFC各自需要多少时间,再从中找出两人花费的最少时间。
#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
#include<cstdio>
#include<queue>
using namespace std;
const int INF = 0x3f3f3f3f;
const int MAXN = 207;
int n, m;
int dir[4][2] = {0, 1, 1, 0, 0, -1, -1, 0};
char maze[MAXN][MAXN];
int vis[MAXN][MAXN];
int cost1[MAXN][MAXN],cost2[MAXN][MAXN];
struct node
{
int x, y;
node(){}
node(int _x, int _y):x(_x),y(_y){}
}Y, M;
void bfs(node st, int cost[][MAXN])
{
memset(vis, 0, sizeof(vis));
memset(cost, 0, sizeof(cost));
queue<node> q;
vis[st.x][st.y] = 1;
cost[st.x][st.y] = 0;
q.push(st);
while(!q.empty())
{
node now = q.front(); q.pop();
for(int i = 0; i < 4; i++)
{
int nx = now.x + dir[i][0];
int ny = now.y + dir[i][1];
if(nx >= 0 && nx < n
&& ny >= 0 && ny < m
&& maze[nx][ny] != '#' && !vis[nx][ny])
{
vis[nx][ny] = 1 ;
cost[nx][ny] = cost[now.x][now.y] + 1;
q.push(node(nx, ny));
}
}
}
}
int main()
{
while(cin >> n >> m)
{
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
{
cin >> maze[i][j];
if(maze[i][j] == 'Y')
{
Y.x = i, Y.y = j;
}
else if(maze[i][j] == 'M')
{
M.x = i, M.y = j;
}
}
bfs(Y, cost1);
bfs(M, cost2);
int ans = INF;
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
{
if(maze[i][j] == '@' && cost1[i][j] != 0 && cost2[i][j] != 0)
{
ans = min(ans, cost1[i][j] + cost2[i][j]);
}
}
cout << ans * 11 << endl;
}
return 0;
}