标签:双向bfs
4 4 Y.#@ .... .#.. @..M 4 4 Y.#@ .... .#.. @#.M 5 5 Y..@. .#... .#... @..M. #...#
66 88 66#include <stdio.h> #include <string.h> #include <iostream> #include <algorithm> #include <queue> using namespace std; const int N=220; const int INF=0xfffffff; int n,m; int ytime[N][N],mtime[N][N]; int map[N][N],num[N][N],vis[N][N]; int temp; void BFS(int x,int y ) { int xx,yy; queue<int>q; xx=x; yy=y; vis[xx][yy]=1; num[xx][yy]=1;//记录二者一共走的步数 q.push(xx); q.push(yy); while(!q.empty()) { xx=q.front(); q.pop(); yy=q.front(); q.pop(); if(map[xx][yy]==1) { if(temp==1) { ytime[xx][yy]=num[xx][yy]-1;//这里很重要 } else { mtime[xx][yy]=num[xx][yy]-1; } } int a ,b; a=xx-1;b=yy; //分四种情况分别讨论 if(a>=1&&!vis[a][b]&&map[a][b]!=-1) { num[a][b]=num[xx][yy]+1; vis[a][b]=1; q.push(a); q.push(b); } a=xx;b=yy-1; if(b>=1&&!vis[a][b]&&map[a][b]!=-1) { num[a][b]=num[xx][yy]+1; vis[a][b]=1; q.push(a); q.push(b); } a=xx+1;b=yy; if(a<=n&&!vis[a][b]&&map[a][b]!=-1) { num[a][b]=num[xx][yy]+1; vis[a][b]=1; q.push(a); q.push(b); } a=xx;b=yy+1; if(b<=m&&!vis[a][b]&&map[a][b]!=-1) { num[a][b]=num[xx][yy]+1; vis[a][b]=1; q.push(a); q.push(b); } } } int main() { int i,j,yx,yy,mx,my; char ch; while(~scanf("%d %d",&n,&m)) { memset(map,0,sizeof(map)); for(i=1;i<=n;i++) { for(j=1;j<=m;j++) { cin>>ch; if(ch=='Y') { yx=i, yy=j; } else if(ch=='M') { mx=i; my=j; } else if(ch=='#') { map[i][j]=-1; } else if(ch=='@') { map[i][j]=1; } } } memset(ytime,0,sizeof(ytime)); memset(mtime,0,sizeof(mtime)); memset(vis,0,sizeof(vis)); memset(num,0,sizeof(num)); temp=1; //标记Y和M的区别 BFS(yx,yy); memset(vis,0,sizeof(vis)); memset(num,0,sizeof(num)); temp=0; BFS(mx,my); int MIN=INF; for(i=1;i<=n;i++) { for(j=1;j<=m;j++) { if(ytime[i][j]&&mtime[i][j]&&(ytime[i][j]+mtime[i][j])<MIN) { MIN=ytime[i][j]+mtime[i][j]; } } } printf("%d\n",MIN*11); } return 0; }
标签:双向bfs
原文地址:http://blog.csdn.net/holyang_1013197377/article/details/44871711