蓝桥杯2019年第十届国赛真题-大胖子走迷宫

题目

题目链接

题解

BFS。


整体思路:将位置信息和时刻信息放入队列,根据时刻信息判断当前时刻小明的大小,如果大小为 1 × 1 1×1 1×1则不能原地停留,因为没意义啊,停留是为了让自己的肚子减小,但是 1 × 1 1×1 1×1时肚子已经最小了,所以只有当大小不是 1 × 1 1×1 1×1时才会进行停留操作,对应到代码上就是位置信息不变,时刻信息+1入队;其他部分就是和基础BFS差不多了,遍历四个方向,如果挺着当前的肚子会遇到障碍,则continue;如果之前走到过该位置,则continue;如果肚子发生越界,则continue。到达终点结束。


真没想到对于原地停留如此处理!而且标记数组居然只用标记位置信息!

代码

#include<bits/stdc++.h>
using namespace std;
const int N = 1010;

int n, k;
string a[N];
int dir[2][4] = {-1, 1, 0, 0, 0, 0, -1, 1};
int st[N * N];  

struct node {
	int first; // 位置(一维) 
	int second; // 到达该位置的时间 
	// 不记录小明每个位置的大小,大小可由时间来判断 
};

int bfs () {
	
	queue <node> q;
	q.push ({2 * n + 2, 0});
	
	st[2*n+2] = 1; // 标记起点 
	
	while (q.size()) {
		
		node t = q.front ();
		q.pop ();
		
		int x = t.first / n;
		int y = t.first % n;
		int tm = t.second;
		
		// 如果当前小明大小不是1 ×1,那么小明可以选择原地踏步 
		int v = 2; // 大小记录为多出的宽度,即5 ×5 = (2*v+1) * (2*v+1),其中v=2,类似的 3 ×3 = (2*1+1) * (2*1+1)
		if (tm >= 2*k) v = 0;
		else if (tm >= k) v = 1;
		if (v) q.push ({t.first, tm + 1}); // 位置不变,时间增加 
		// 放在遍历四个方向的for循环外面 
		
		for (int i = 0;i < 4;i ++) {
			int tx = x + dir[0][i], ty = y + dir[1][i], flag = 0;
			int tnext = tx * n + ty;
			
			// 越界 (加上肚子) 
			if (tx - v < 0 || ty - v < 0 || tx + v >= n || ty + v >= n) continue;
			
			// 状态是否遇到过 
			if (st[tnext]) continue;
			
			// 遇到障碍物 (加上肚子) 
			for (int j = -v;j <= v;j ++)
				for (int k = -v;k <= v;k ++)
					if (a[tx+j][ty+k] == '*') {
						flag = 1;
						break;
					}
			if (flag) continue;
			
			if (tx == n-3 && ty == n-3) return tm+1; // 遇到就跳出,而不是在外面判断是为了减少次数 
			
			st[tnext] = 1;
			q.push ({tnext, tm + 1}); 
		}
	}
	return -1;
}

int main()
{
	cin >> n >> k;
	for (int i = 0;i < n;i ++)
	cin >> a[i];
	
	cout << bfs ();	

	return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不牌不改

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值