搜索专题-Find a way

topic:

Pass a year learning in Hangzhou, yifenfei arrival hometown Ningbo at finally. Leave Ningbo one year, yifenfei have many people to meet. Especially a good friend Merceki.
Yifenfei’s home is at the countryside, but Merceki’s home is in the center of city. So yifenfei made arrangements with Merceki to meet at a KFC. There are many KFC in Ningbo, they want to choose one that let the total time to it be most smallest.
Now give you a Ningbo map, Both yifenfei and Merceki can move up, down ,left, right to the adjacent road by cost 11 minutes.

 input:

The input contains multiple test cases.
Each test case include, first two integers n, m. (2<=n,m<=200).
Next n lines, each line included m character.
‘Y’ express yifenfei initial position.
‘M’    express Merceki initial position.
‘#’ forbid road;
‘.’ Road.
‘@’ KCF

output:

For each test case output the minimum total time that both yifenfei and Merceki to arrival one of KFC.You may sure there is always have a KFC that can let them meet.


思路:

从两个人出发,记录到每一个点的距离,最后遍历找的KFC,算出到它的距离,进行比较,值得注意的是,要判断两个人是否可以到达KFC,距离为0话,无法到达,就去除这个店。

代码(两次bfs):

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include

const int N = 210;
using namespace std;
typedef pair PII;
int n,m,yx,yy,mx,my;
char a[N][N];
int book[N][N]; //判断是否重复
int dist1[N][N]; //记录距离
int dist2[N][N]; //记录距离
int dx[4] = {0,0,1,-1}; //方向
int dy[4] = {1,-1,0,0};
void bfs1(int x,int y){
	queue q;
	q.push({x,y});
	book[x][y] = 1;
	while(q.size()){
		PII t = q.front();
		q.pop();
		for(int i = 0;i < 4;i ++){
			int tx = t.first + dx[i];
			int ty = t.second + dy[i];
			if(book[tx][ty]==0&&a[tx][ty]!='#'&&tx>=0&&tx=0&&ty q;
	q.push({x,y});
	book[x][y] = 1;
	while(q.size()){
		PII t = q.front();
		q.pop();
		for(int i = 0;i < 4;i ++){
			int tx = t.first + dx[i];
			int ty = t.second + dy[i];
			if(book[tx][ty]==0&&a[tx][ty]!='#'&&tx>=0&&tx=0&&ty> a[i][j];
				if(a[i][j] == 'Y'){
					yx = i,yy = j;
				}
				if(a[i][j] == 'M'){
					mx = i,my = j;
				}
			}
		}
		memset(book,0,sizeof book); //记得归0
		memset(dist1, 0, sizeof dist1);
		bfs1(yx,yy);
		memset(book,0,sizeof book);
		memset(dist2, 0, sizeof dist2);
		bfs2(mx,my);
		int ans = 99999999;
		for(int i = 0;i < n;i ++){
			for(int j = 0;j < m;j ++){
				if(a[i][j] == '@'&&dist1[i][j]!=0&&dist2[i][j]!=0){ //可能有无法到达的KFC,dist = 0,去除这个情况
					ans = min(ans,dist1[i][j]*11+dist2[i][j]*11);
				}
			}
		}
		cout << ans << endl;
	}
	return 0;
}

这个题写了我整整3个小时,呜呜呜。首先思路很重要,要想清楚怎样走,bfs次数最少,这个尤其重要,没有想清楚,会超时,其次,考虑无法到达的情况,还有一些细节,要注意!

你可能感兴趣的:(c++,算法,数据结构,广度优先)