Two persons (Y and M) to meet at the ' @ ', there is an indefinite ' @ ' in the picture;
Do the BFS once for everyone, then enumerate each ' @ ' position
#include "stdio.h" #include "string.h" #include "queue" using namespace std;const int Inf=0x7fffffff;const int dir[4][2]={ {1,0},{-1,0},{0,1},{0,-1}};struct node{int x,y,t;}; int Y_n,y_m,m_n,m_m,n,m;char str[210][210];int sum[210][210],mark[210][210];int Min (int a,int b) {if (a<b) return A; else return b;} int judge (int x,int y) {if (x<0 | | y<0 | | x>=n | | y>=m) return 0; if (mark[x][y]==1) return 0; if (str[x][y]== ' # ') return 0; return 1;} void BFs () {queue<node>q,qq; Node Cur,next; int i; Cur.x=y_n; Cur.y=y_m; cur.t=0; memset (Mark,0,sizeof (Mark)); Mark[y_n][y_m]=1; sum[cur.x][cur.y]=0; Q.push (cur); while (!q.empty ()) {Cur=q.front (); Q.pop (); for (i=0;i<4;i++) {next.x=cur.x+dir[i][0]; NEXT.Y=CUR.Y+DIR[I][1]; if (judge (NEXT.X,NEXT.Y) ==0) continue; next.t=cur.t+1; Mark[next.x][next.y]=1; sum[next.x][next.y]=next.t; Q.push (next); }} cur.x=m_n; Cur.y=m_m; cur.t=0; memset (Mark,0,sizeof (Mark)); Mark[m_n][m_m]=1; Qq.push (cur); while (!qq.empty ()) {Cur=qq.front (); Qq.pop (); for (i=0;i<4;i++) {next.x=cur.x+dir[i][0]; NEXT.Y=CUR.Y+DIR[I][1]; if (judge (NEXT.X,NEXT.Y) ==0) continue; next.t=cur.t+1; Mark[next.x][next.y]=1; sum[next.x][next.y]+=next.t; Qq.push (next); }}}int Main () {int i,j,ans; while (scanf ("%d%d", &n,&m)!=eof) {for (i=0;i<n;i++) scanf ("%s", Str[i]); for (i=0;i<n;i++) for (j=0;j<m;j++) if (str[i][j]== ' Y ') {y_n=i; Y_m=j; } else if (str[i][j]== ' M ') {m_n=i; M_m=j; } memset (Sum,-1,sizeof (sum)); BFS (); Ans=inf; for (i=0;i<n;i++) for (j=0;j<m;j++) if (str[i][j]== ' @ ' && sum[i][j]!=-1) ans=m In (Ans,sum[i][j]); printf ("%d\n", ans*11); } return 0;}
HDU 2612 Water BFS