广搜两遍找出Y和M到每个KFC的最短距离,然后找一个和最小的输出……
本来打算两个人一起走,碰头就输出。
结果发现如果最短距离的KFC离某一个人很近,但离另一个很远,而又有一个KFC在两人之间的时候,答案就不对了。
结果只能用这种笨办法了。
#include <stdio.h>
#include <string.h>
#define INF 9999
typedef struct{
int x,y,t;
}QUEUE;
char map[203][203];
const int dirc[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
int n,m,yVisit[203][203],mVisit[203][203];
QUEUE q1[80000],q2[80000];
int logic(int x, int y){
return (x>=0&&y>=0&&x<n&&y<m&&map[x][y]!='#');
}
int bfs(int yStrX, int yStrY, int mStrX, int mStrY){
int yTop,yTail,mTop,mTail,yTime,mTime,i;
int yNextX,yNextY,yNextTime,mNextX,mNextY,mNextTime;
yTop = yTail = mTop = mTail = 0;
q1[yTail].x = yStrX;
q1[yTail].y = yStrY;
q1[yTail++].t = 0;
yVisit[yStrX][yStrY] = 1;
q2[mTail].x = mStrX;
q2[mTail].y = mStrY;
q2[mTail++].t = 0;
mVisit[mStrX][mStrY] = 1;
while(yTop < yTail || mTop < mTail){
if(yTop < yTail){
yStrX = q1[yTop].x;
yStrY = q1[yTop].y;
yTime = q1[yTop++].t;
for(i = 0; i < 4; i++){
yNextX = yStrX + dirc[i][0];
yNextY = yStrY + dirc[i][1];
yNextTime = yTime + 1;
if(logic(yNextX,yNextY) && !yVisit[yNextX][yNextY]){
yVisit[yNextX][yNextY] = yNextTime;
q1[yTail].x = yNextX;
q1[yTail].y = yNextY;
q1[yTail++].t = yNextTime;
}
}
}
if(mTop < mTail){
mStrX = q2[mTop].x;
mStrY = q2[mTop].y;
mTime = q2[mTop++].t;
for(i = 0; i < 4; i++){
mNextX = mStrX + dirc[i][0];
mNextY = mStrY + dirc[i][1];
mNextTime = mTime + 1;
if(logic(mNextX,mNextY) && !mVisit[mNextX][mNextY]){
mVisit[mNextX][mNextY] = mNextTime;
q2[mTail].x = mNextX;
q2[mTail].y = mNextY;
q2[mTail++].t = mNextTime;
}
}
}
}
return 0;
}
int main (void){
int i,j,yStrX,yStrY,mStrX,mStrY,min;
while(~scanf("%d%d",&n,&m)){
getchar();
memset(yVisit,0,sizeof(yVisit));
memset(mVisit,0,sizeof(mVisit));
for(i = 0; i < n; i++){
gets(map[i]);
for(j = 0; j < m; j++){
if(map[i][j] == 'Y'){
yStrX = i;
yStrY = j;
}
else if(map[i][j] == 'M'){
mStrX = i;
mStrY = j;
}
}
}
bfs(yStrX,yStrY,mStrX,mStrY);
min = INF;
for(i = 0; i < n; i++)
for(j = 0; j < m; j++){
if(map[i][j] == '@' && yVisit[i][j] && mVisit[i][j])
if(min > yVisit[i][j] + mVisit[i][j])
min = yVisit[i][j] + mVisit[i][j];
}
printf("%d\n",min * 11);
}
return 0;
}