学习总结!

最近主要在学习java,刷题比较少。

 这道题利用了BFS算法,其中这道题他有两个起点,我们可以分别对两个起点进行bfs算法求解,然后找出两个起点到某一个kfc的最小值,再乘以11即可。

#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
const int inf = 0x3f3f3f3f;
int n, m, cnt;
char mp[220][220];
bool vis[220][220];
int a[220][220];
int b[220][220];
int d[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
struct node
{
	int x, y, step;
};
void bfs(int x, int y, int l[220][220])
{
	memset(vis, 0, sizeof(vis));
	queue<node> q;
	node a, ne;
	a.x = x; a.y = y; a.step = 0;
	q.push(a);
	vis[x][y] = 1;
	while(!q.empty())
	{
		a = q.front();
		q.pop();
		if(mp[a.x][a.y] == '@')
		{
			l[a.x][a.y] = a.step;
		}
		for(int i = 0; i < 4; i++)
		{
			ne.x = a.x + d[i][0];
			ne.y = a.y + d[i][1];
			if(ne.x < 0 || ne.x >= n || ne.y < 0 || ne.y >= m || vis[ne.x][ne.y] == 1 || mp[ne.x][ne.y] == '#')
				continue;
			ne.step = a.step + 1;
			q.push(ne);
			vis[ne.x][ne.y] = 1;
		}
	}
	return;
}
int main()
{
	int i, j, be1, en1, be2, en2, sum;
	while(scanf("%d%d", &n, &m) != EOF)
	{
		sum = inf;
		cnt = 0;
		for(i = 0; i < n; i++)
		{
			scanf("%s", &mp[i]);
			for(j = 0; j < m; j++)
			{
				if(mp[i][j] == 'Y')
				{
					be1 = i;
					en1 = j;
				}
				else if(mp[i][j] == 'M')
				{
					be2 = i;
					en2 = j;
				}
			}
		}
		bfs(be1, en1, a);
		bfs(be2, en2, b);
		for(i = 0; i < n; i++){
			for(j = 0; j < m; j++){
				if(mp[i][j] == '@' && vis[i][j] == 1)
				{
					sum = min(sum, a[i][j]+b[i][j]);
				}
			}
		}
		printf("%d\n", sum*11);
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值