//这题坑了我一晚上,用C++交不行,结果用C或者G++却过来,哎。。。。这题让我明白,如果用BFS,要保存到达“@”点的步数,bfs一直搜索,直到没发走才停。让后在主函数中进行输出比较。。。
AC代码:
#include<stdio.h> #include<string.h> #include<algorithm> using namespace std; #define N 205 char map[N][N]; int vis[N][N]; int dp1[N][N],dp2[N][N]; int x1,y1,x2,y2; struct node { int x,y,step; }queue[N*N]; int dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}}; int n,m; void bfs1() { struct node now,pre; queue[0].x=x1; queue[0].y=y1; queue[0].step=0; int e=0,h=1; while(e<h) { pre=queue[e]; for(int i=0;i<4;i++) { now.x=pre.x+dir[i][0]; now.y=pre.y+dir[i][1]; now.step=pre.step+1; if(now.x>=0&&now.x<n&&now.y>=0&&now.y<m&&!vis[now.x][now.y]&&map[now.x][now.y]!='#') { dp1[now.x][now.y]=now.step; vis[now.x][now.y]=1; queue[h++]=now; } } e++; } return; } void bfs2() { struct node now,pre; queue[0].x=x2; queue[0].y=y2; queue[0].step=0; int e=0,h=1; while(e<h) { pre=queue[e]; for(int i=0;i<4;i++) { now.x=pre.x+dir[i][0]; now.y=pre.y+dir[i][1]; now.step=pre.step+1; if(now.x>=0&&now.x<n&&now.y>=0&&now.y<m&&!vis[now.x][now.y]&&map[now.x][now.y]!='#') { dp2[now.x][now.y]=now.step; vis[now.x][now.y]=1; queue[h++]=now; } } e++; } return; } int main() { while(scanf("%d%d",&n,&m)!=EOF) { memset(dp1,0,sizeof(dp1)); memset(dp2,0,sizeof(dp2)); int i,j; for(i=0;i<n;i++) { scanf("%s",map[i]); } for(i=0;i<n;i++) { for(j=0;j<m;j++) { if(map[i][j]=='M') { x1=i; y1=j; } if(map[i][j]=='Y') { x2=i; y2=j; } } } memset(vis,0,sizeof(vis)); bfs1(); memset(vis,0,sizeof(vis)); bfs2(); int MIN=N*N; for(i=0;i<n;i++) { for(j=0;j<m;j++) { if(map[i][j]=='@'&&dp1[i][j]&&dp2[i][j]) { MIN=min(MIN,dp1[i][j]+dp2[i][j]); } } } printf("%d\n",MIN*11); } return 0; }