点此进入题目:题目链接
思路:开始想用 双向BFS 但是 写着写着不会了,又改用单向BFS。跑两次图,然后找到最小值即可
AC代码:
#include<iostream>
#include<cstring>
#include<string.h>
#include<queue>
#include<stack>
#include<vector>
using namespace std;
const int maxn = 205;
const int INF = (1 << 31) - 1;
char maze[maxn][maxn];
int vis[maxn][maxn];
int dist1[maxn][maxn];
int dist2[maxn][maxn];
int n, m;
int X[4] = {1, -1, 0, 0};
int Y[4] = {0, 0, 1, -1};
struct node{
int x, y;
};
bool check(node now){
if(now.x < 1 || now.x > n || now.y < 1 || now.y > m || maze[now.x][now.y] == '#'){
return 0;
}
return 1;
}
int BFS(node s, int dist[][maxn]){
memset(vis, 0, sizeof(vis));
queue<node> q;
q.push(s);
vis[s.x][s.y] = 1;
dist[s.x][s.y] = 0;
node front, next;
while(!q.empty()){
front = q.front();
q.pop();
for(int i = 0; i < 4; i++){
next.x = front.x + X[i];
next.y = front.y + Y[i];
if(check(next) && vis[next.x][next.y] == 0){
dist[next.x][next.y] = dist[front.x][front.y] + 1;
vis[next.x][next.y] = 1;
q.push(next);
}
}
}
}
int main(){
while(cin >> n >> m){
node start, end;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
cin >> maze[i][j];
if(maze[i][j] == 'Y'){
start.x = i;
start.y = j;
}
if(maze[i][j] == 'M'){
end.x = i;
end.y = j;
}
}
}
memset(dist1, 0, sizeof(dist1));
memset(dist2, 0, sizeof(dist2));
BFS(start, dist1);
BFS(end, dist2);
int ans = INF;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
if(ans > dist1[i][j] + dist2[i][j] && dist1[i][j] != 0 && dist2[i][j] != 0 && maze[i][j] == '@'){
ans = dist1[i][j] + dist2[i][j];
}
}
}
ans *= 11;
cout << ans << endl;
}
return 0;
}