HDU 2612 Find a way

HDU 2612 Find a way

题目大意:
y和m要去肯德基聚餐,图中有多个kfc,他们要选的那个kfc必须到彼此的所用时间之和最小,问最少需要多少时间。

题目思路:
将Y和M分开进行BFS,
然后根据二者到达KFC的时间总和,取用时最少的kfc
推荐与这题类似并且稍微复杂的题:UVA 11624

具体代码:

#include
#include
#include
#include

using namespace std;

int step[4][2] = {
      {
     1,0},{
     -1,0},{
     0,1},{
     0,-1} };
int roads[205][205];
int cost_by_Y[205][205]; //表示Y到该处的时间
int cost_by_M[205][205];	//表示M到该处的时间
int visit[205][205];	
const int INF = 1e5;
int ans = INF;
int r, c;

void cmp_time()
{
     
	for (int i = 0; i < r; i++)
		for (int j = 0; j < c; j++)
		{
     
			if ( roads[i][j]==2) {
     
				if (cost_by_Y[i][j] + cost_by_M[i][j]<ans)	
				{
     
					ans = cost_by_Y[i][j] + cost_by_M[i][j];
				}
			}
		}
}
void bfs(int x, int y, int cost[][205])
{
     
	for (int i = 0; i < r; i++)
		for (int j = 0; j < c; j++)
			 cost[i][j]=INF,visit[i][j] = 0;//初始化
	queue<pair<int, int>> q;
	q.push(pair<int, int>(x, y));
	visit[x][y] = 1;
	cost[x][y] = 0;
	
	while (!q.empty())
	{
     
		pair<int, int> t = q.front();
		q.pop();
		for (int i = 0; i < 4; i++)
		{
     
			int x = t.first, y = t.second;
			x += step[i][0], y += step[i][1];
			if (x >= 0 && x < r &&y >= 0 && y < c && !visit[x][y] && roads[x][y]) {
     
				visit[x][y] = 1;
				cost[x][y] = cost[t.first][t.second] + 1;
				q.push(pair<int, int>(x, y));
			}
		}
	}

}
int main()
{
     
	while (cin >> r >> c)
	{
     
		int x1, y1, x2, y2;
		for (int i = 0; i < r; i++)
		{
     
			string s;
			cin >> s;
			for (int j = 0; j < c; j++)
			{
     
				if (s[j] == '#')roads[i][j] = 0;
				else if (s[j] == '.')roads[i][j] = 1;
				else if (s[j] == '@')roads[i][j] = 2;
				else if (s[j] == 'Y') {
     
					roads[i][j] = 1;
					x1 = i, y1 = j;
				}
				else if(s[j]=='M'){
     
					roads[i][j] = 1;
					x2 = i, y2 = j;	
				}
			}
		}
		bfs(x1, y1, cost_by_Y);
		bfs(x2, y2, cost_by_M);
		cmp_time();
		printf("%d\n", ans * 11);
		ans = INF;
	}
	return 0;
}

你可能感兴趣的:(OJ题解,bfs,&,dfs)