hdu-2612 两次bfs

http://acm.hdu.edu.cn/showproblem.php?pid=2612

两次bfs, 记录到每个KFC的最短时间。选取最短时间。

#include <stdio.h>
#include <iostream>
#include <string>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <vector>

using namespace std;

int n, m;

int dir[4][2] = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };

int check(int x, int y)
{
	if (x >= 1 && x <= n && y >= 1 && y <= m)
		return 1;
	return 0;
}

struct node
{
	int x;
	int y;
	int t1, t2;
	char c;
}p[210][210];

int vis[210][210];
int sx, sy;
int ex, ey;

void bfs(int x,int y)
{
	memset(vis,0,sizeof(vis)); 
	queue<node> q;
	node qq, qqq;
	qq.x = x;
	qq.y = y;
	qq.t1 = 0;
	p[x][y].t1 = 0;
	vis[x][y] = 1;
	q.push(qq);

	while (!q.empty())
	{
		qq = q.front();
		q.pop();

		for (int i = 0; i < 4; i++)
		{
			int x = qq.x + dir[i][0];
			int y = qq.y + dir[i][1];
			if (!check(x, y) || vis[x][y] || p[x][y].c == '#')
				continue;

			vis[x][y] = 1;

			qqq.x = x;
			qqq.y = y;
			qqq.t1 = qq.t1 + 1; 
			p[x][y].t1 = qqq.t1;
			q.push(qqq);
		}
	}
	return;
}

void bfs1(int x, int y)
{
	memset(vis, 0, sizeof(vis));
	queue<node> q;
	node qq, qqq;
	qq.x = x;
	qq.y = y;
	qq.t2 = 0;
	p[x][y].t2 = 0;
	vis[x][y] = 1;
	q.push(qq);

	while (!q.empty())
	{
		qq = q.front();
		q.pop();

		for (int i = 0; i < 4; i++)
		{
			int x = qq.x + dir[i][0];
			int y = qq.y + dir[i][1];
			
			if (!check(x, y) || vis[x][y] || p[x][y].c == '#')
				continue;

			vis[x][y] = 1;

			qqq.x = x;
			qqq.y = y;
			qqq.t2 = qq.t2 + 1;
			p[x][y].t2 = qqq.t2;
			q.push(qqq);
		}
	}
	return;
}

int main()
{
	while (cin >> n >> m)
	{
		getchar();
		for (int i = 1; i <= n; i++)
		{
			for (int j = 1; j <= m; j++)
			{
				cin >> p[i][j].c;
				if (p[i][j].c == 'Y')
				{
					sx = i;
					sy = j;
				}
				if (p[i][j].c == 'M')
				{
					ex = i;
					ey = j;
				}
			}
			getchar();
		}

		bfs(sx,sy);
		bfs1(ex,ey);

		for (int i = 1; i <= n; i++)
			for (int j = 1; j <= m; j++)
			{
				if (p[i][j].c == '@')
				{
					p[i][j].t1 = (p[i][j].t1+p[i][j].t2);
				}
			}
		int ans = 10000000;

		for (int i = 1; i <= n; i++)
			for (int j = 1; j <= m; j++)
			{
				if (p[i][j].c == '@')
				{
					ans = min(p[i][j].t1, ans);
				}
			}

		ans *= 11;
		cout << ans << endl;
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值