4 4 Y.#@ .... .#.. @..M 4 4 Y.#@ .... .#.. @#.M 5 5 Y..@. .#... .#... @..M. #...#
66 88 66
#include <stdio.h> #include <string.h> char map[211][211]; //地图 int book[211][211]; //标记数组 int ans[211][211]; //记录距离的数组 int a[4][2]={1,0,-1,0,0,1,0,-1},m,n; struct Team { int x,y,s; }que[100000]; void bfs(int startx,int starty) { int head,tail; int tx,ty,i; head=tail=0; que[tail].x=startx; que[tail].y=starty; que[tail++].s=0; book[startx][starty]=1; while(head<tail) { for(i=0;i<4;i++) { tx=que[head].x+a[i][0]; ty=que[head].y+a[i][1]; if(tx<0||tx>=n||ty<0||ty>=m||book[tx][ty]||map[tx][ty]=='#') continue; if(map[tx][ty]=='@') ans[tx][ty]+=que[head].s+1; //在ans记录路程. book[tx][ty]=1; que[tail].x=tx; que[tail].y=ty; que[tail++].s=que[head].s+1; } head++; } } int main() { int i,j,min=99; while(scanf("%d%d",&n,&m)!=EOF) { memset(ans,0,sizeof(ans)); memset(book,0,sizeof(book)); for(i=0;i<n;i++) scanf("%s",map[i]); int startx,starty; for(i=0;i<n;i++) for(j=0;j<m;j++) if(map[i][j]=='Y') startx=i,starty=j; bfs(startx,starty); //从第一个人开始展开BFS. memset(book,0,sizeof(book)); for(i=0;i<n;i++) for(j=0;j<m;j++) if(map[i][j]=='M') startx=i,starty=j; bfs(startx,starty); //从第二个人开始展开BFS int min=99999; for(i=0;i<n;i++) for(j=0;j<m;j++) if(ans[i][j]<min&&ans[i][j]) min=ans[i][j]; printf("%d\n",11*min); } return 0; }
C语言BFS(4)___Find a way(Hdu 2612)
原文地址:http://blog.csdn.net/y1196645376/article/details/42079827