题目:N - Find a way
思路:多源BFS,首先将两个人到达每个点用的最小时间求出来,然后遍历图,找到所有的餐馆,找到两个人到达餐馆用的最小时间
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#define fi first
#define se second
#define PII pair<int, int>
using namespace std;
const int INF = 0x3f3f3f3f;
const int N = 202;
PII X, Y;
char mp[N][N];
int st[N][N];
int n, m;
int dir[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
int step1[N][N], step2[N][N];
bool check(int x, int y)
{
if(x < 1 || y < 1 || x > n || y > m || st[x][y] || mp[x][y] == '#') return false;
return true;
}
void bfs(PII v, int step[][N])
{
memset(st, 0, sizeof st);
queue<PII> qu;
qu.push(v);
st[v.fi][v.se] = 1;
while(!qu.empty())
{
PII t = qu.front();
qu.pop();
for(int i = 0; i < 4; i ++)
{
int x = t.fi + dir[i][0];
int y = t.se + dir[i][1];
if(!check(x, y)) continue;
step[x][y] = step[t.fi][t.se] + 1;
st[x][y] = 1;
qu.push(make_pair(x, y));
}
}
}
int main()
{
while(cin >> n >> m)
{
memset(step1, 0, sizeof step1);
memset(step2, 0, sizeof step2);
for(int i = 1; i <= n; i ++)
{
for(int j = 1; j <= m; j ++)
{
cin >> mp[i][j];
if(mp[i][j] == 'Y')
X = make_pair(i, j);
if(mp[i][j] == 'M')
Y = make_pair(i, j);
}
}
bfs(X, step1);
bfs(Y, step2);
int res = INF;
for(int i = 1; i <= n; i ++)
{
for(int j = 1; j <= m; j ++)
{
if(mp[i][j] == '@' && step1[i][j] && step2[i][j])
res = min(res, step1[i][j] + step2[i][j]);
}
}
cout << res * 11 << endl;
}
}