题目链接:
传送门
#include<iostream>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
const int N = 205;
int op[4][2]= {{0,1},{0,-1},{1,0},{-1,0}},n,m,Yx,Yy,Mx,My,theend[N][2],ans1[N][N],ans2[N][N];
char theMap[N][N];
struct node {
int x,y;
};
//判断是否在边界内
bool intheMap(int x,int y) {
return x>=0&&y>=0&&x<n&&y<m;
}
//第一个人进行bfs
int bfs1(int x,int y) {
memset(ans1, 0, sizeof(ans1));
ans1[x][y] = 1;
queue<node> q;
node start = {x,y};
q.push(start);
while(!q.empty()) {
node cur = q.front();
q.pop();
for(int i=0; i<4; i++) {
int curX = cur.x+op[i][0];
int curY = cur.y+op[i][1];
if(intheMap(curX,curY)&&theMap[curX][curY]!='#'&&!ans1[curX][curY]) {
ans1[curX][curY]=ans1[cur.x][cur.y]+1;
node news= {curX,curY};
q.push(news);
}
}
}
}
//第二个人进行bfs
int bfs2(int x,int y) {
memset(ans2, 0, sizeof(ans2));
ans2[x][y] = 1;
queue<node> q;
node start = {x,y};
q.push(start);
while(!q.empty()) {
node cur = q.front();
q.pop();
for(int i=0; i<4; i++) {
int curX = cur.x+op[i][0];
int curY = cur.y+op[i][1];
if(intheMap(curX,curY)&&theMap[curX][curY]!='#'&&!ans2[curX][curY]) {
ans2[curX][curY]=ans2[cur.x][cur.y]+1;
node news= {curX,curY};
q.push(news);
}
}
}
}
int main() {
int sx, sy, tx, ty, x, y, ans;
while(scanf("%d%d", &n, &m) != EOF) {
ans = 999999999;
for(int i = 0; i < n; i++) scanf("%s", theMap[i]);
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(theMap[i][j] == 'Y') sx = i, sy = j;
}
}
bfs1(sx, sy);
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(theMap[i][j] == 'M') sx = i, sy = j;
}
}
bfs2(sx, sy);
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(theMap[i][j] == '@' && ans1[i][j] && ans2[i][j]) ans = min(ans, (ans1[i][j] + ans2[i][j] - 2) * 11);
}
}
printf("%d\n", ans);
}
return 0;
}
这道题是用两个BFS来搜索,找到Y和M的点,然后对这几个点进行bfs搜出他们到目标点,然后找到它们的最短路径然后把总路径乘11。最后输出答案。