#include "iostream"
#include "cstring"
#include "queue"
#define INF 0x3f3f3f3f
using namespace std;
char a[][];
int n, m;
struct node{
int x, y;
int step;
}now,start1,start2;
//记录
char vis[][];
int kfc1[][];
int kfc2[][];
bool check(node x){
if(x.x >= && x.x < n && x.y >= && x.y < m) return true;
else return false;
}
void bfs(node now,int(*kfc)[]){
queue<node>s;
memcpy(vis,a,sizeof(a));
int dx[] = {,-,,};
int dy[] = {,,,-};
now.step = ;
s.push(now);
while(!s.empty()){
now = s.front();s.pop();
if (vis[now.x][now.y]=='#')continue;
if(vis[now.x][now.y]=='@') kfc[now.x][now.y] = now.step;
vis[now.x][now.y] = '#';
for(int i = ; i < ; i++){
node next;
next.x = now.x + dx[i];
next.y = now.y + dy[i];
next.step = now.step + ;
if(check(next)){
if(vis[next.x][next.y] == '.' || vis[next.x][next.y] == '@')
s.push(next);
else continue;
}
}
}
// for(int i = 0;i < n; i++){
// for(int j = 0; j < m; j++){
// cout << kfc[i][j]<<" ";
// }
// cout << endl;
// }
}
int main(){
while(scanf("%d%d",&n,&m)!=EOF){
for(int i = ; i < n; i++){
scanf("%s",a[i]);
}
for(int i = ; i < n; i++)
for(int j = ; j < m; j++){
if(a[i][j]=='Y'){
start1.x = i;
start1.y = j;
start1.step = ;
}
if(a[i][j]=='M'){
start2.x = i;
start2.y = j;
start2.step = ;
}
}
// cout<<start1.x<<" " <<start1.y<<endl;
// cout<<start2.x<<" " <<start2.y<<endl;
memset(kfc1,,sizeof(kfc1));
memset(kfc2,,sizeof(kfc2));
bfs(start1,kfc1);
bfs(start2,kfc2);
int min = INF;
for(int i = ; i < n; i++)
for(int j = ; j < m; j++){
if(kfc1[i][j]!=INF && kfc2[i][j]!=INF&& (kfc1[i][j]+kfc2[i][j])< min)
min = kfc1[i][j] + kfc2[i][j];
// cout<<"min "<<min<<endl;
}
printf("%d\n",min*);
}
}
还是要注意,continue不加会超时和超内存,一定是因为栈的问题导致的。 还有就是千万注意&&和||,这些细节害我查了3个小时的错。
最好是push完!!就标记已经访问过