hdu2612.。。。
水了一天bfs了
题意:2个人分别从Y,M出发,到达其中任意一个“@” (图中有多个“@”点),2人到达的必须是同一个“@”点,求最短的路程和
思路:bfs搜2次,用一个2维数组记录到达各个“@”的距离之和 再遍历求最小的(用一个数组就可以的原因是Y可以到达的地方M一定也能到达,因为Y,M必然可以相遇,所以Y和M必然是连通,一开始还怀疑了一下自己)
#include "map" #include "queue" #include "math.h" #include "stdio.h" #include "string.h" #include "iostream" #include "algorithm" 19:01:0019:01:162016-08-05#define abs(x) x > 0 ? x : -x #define max(a,b) a > b ? a : b #define min(a,b) a < b ? a : b using namespace std; int d[4][2] = {{0,1},{1,0},{0,-1},{-1,0}}; int Map[205][205],l[205][205]; bool vis[205][205]; struct Node { int xx,yy; int step; }; void Bfs(int x,int y) { memset(vis,0,sizeof(vis)); Node now,next; queue<Node>Q; now.xx = x; now.yy = y; now.step = 0; vis[x][y] = 1; Q.push(now); while(!Q.empty()) { now = Q.front(); Q.pop(); if(Map[now.xx][now.yy]==6) l[now.xx][now.yy] += now.step; for(int i=0; i<4; i++) { next.xx = now.xx + d[i][0]; next.yy = now.yy + d[i][1]; next.step = now.step + 1; if(Map[next.xx][next.yy]!=0 && !vis[next.xx][next.yy]) { vis[next.xx][next.yy] = 1; Q.push(next); } } } } int main() { int x1,y1,x2,y2,n,m,ans,i,j; char c; while(scanf("%d%d",&n,&m)!=EOF) { memset(Map,0,sizeof(Map)); memset(l,0,sizeof(l)); for(i=1; i<=n; i++) { getchar(); for(j=1; j<=m; j++) { scanf("%c",&c); if(c=='.') Map[i][j] = 1; if(c=='#') Map[i][j] = 0; if(c=='Y') { Map[i][j] = 1; x1 = i,y1 = j; } if(c=='M') { Map[i][j] = 1; x2 = i,y2 = j; } if(c=='@') Map[i][j] = 6; } } Bfs(x1,y1); Bfs(x2,y2); ans = 99999999; for(i=1; i<=n; i++) for(j=1; j<=m; j++) { if(l[i][j]!=0) ans = min(ans,l[i][j]); } printf("%d\n",ans*11); } return 0; }