1.题目链接。题目的意思就不用翻译了,很容易看懂。看到这个问题,我们知道解决方案肯定是bfs寻找最短路。我们可以bfs打表,打出来起点到所有点的路,然后寻找二者之和最短的即可。实际也不难操作。AC代码如下:
#include<bits/stdc++.h>
#include<iostream>
#include<queue>
#pragma warning(disable:4996)
const int inf = 1e9 + 10;
using namespace std;
char mp[210][210];
int dist1[210][210];
int dist2[210][210];
int yx, yy;
int mx, my;
struct node
{
int x;
int y;
int step;
};
int dir[4][2] = { 1,0,0,1,0,-1,-1,0 };
int vis[210][210];
queue<node>Q;
int n, m;
void bfs(node p, int dis[][210])
{
Q.push(p);
memset(dis, 0, sizeof(dis));
memset(vis,0,sizeof(vis));
while (!Q.empty())
{
p = Q.front();
Q.pop();
node q;
for (int i = 0; i < 4; i++)
{
q.x = p.x + dir[i][0];
q.y = p.y + dir[i][1];
q.step = p.step + 1;
if (q.x >= 0 && q.x < n&&q.y >= 0 && q.y < m && !vis[q.x][q.y]&&mp[q.x][q.y]!='#')
{
vis[q.x][q.y] = 1;
dis[q.x][q.y] = q.step;
Q.push(q);
}
}
}
}
int main()
{
while (~scanf("%d%d", &n, &m))
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
scanf(" %c", &mp[i][j]);
if (mp[i][j] == 'Y')
{
yx = i;
yy = j;
}
if (mp[i][j] == 'M')
{
mx = i;
my = j;
}
}
}
int min = inf;
node p;
p.x = yx;
p.y = yy;
p.step = 0;
bfs(p, dist1);
p.x = mx;
p.y = my;
p.step = 0;
bfs(p, dist2);
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (mp[i][j] == '@')
{
if (dist1[i][j]!=0 && dist2[i][j]!=0)
{
if (dist1[i][j] + dist2[i][j] < min)
{
min = dist1[i][j] + dist2[i][j];
}
}
}
}
}
cout << (long long)min * 11 << endl;
}
}