牛客寒假算法基础集训营6 J 迷宫 搜索

题解

因为在路径代价为1的情况下BFS最先到达的地方就是最优的,不会出现先如果能直接左走到却先右走走再左走走的情况,而且向上/下走又不能代替左/右走。所以只需要进行一次普普通通的BFS即可。
直接在队列节点上加上两个标记,表示当前节点剩余的可以往左/右走的次数然后对第一次走到的节点ans++并且标记走过。

AC代码

#include <stdio.h>
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

const int INF = 0x3f3f3f3f;
const int MAXN = 1e3 + 10;
int dir[4][2] = { -1, 0, 1, 0, 0, -1, 0, 1 };
char g[MAXN][MAXN];
bool vis[MAXN][MAXN];
int n, m, x, y, l, r, ans;

struct node
{
	int x, y, l, r; //剩余左右移动次数
};
void BFS()
{
	queue<node> q;
	q.push({ x, y, l, r });
	vis[x][y] = 1;
	while (!q.empty())
	{
		ans++;
		int x = q.front().x, y = q.front().y, l = q.front().l, r = q.front().r;
		q.pop();
		for (int i = 0; i < 4; i++)
		{
			int xx = x + dir[i][0], yy = y + dir[i][1];
			if (xx >= 1 && xx <= n && yy >= 1 && yy <= m && g[xx][yy] == '.' &&
				!vis[xx][yy] && (i != 2 || l) && (i != 3 || r))
				vis[xx][yy] = 1, q.push({ xx, yy, l - (i == 2), r - (i == 3) });
		}
	}
}
int main()
{
#ifdef LOCAL
	freopen("C:/input.txt", "r", stdin);
#endif
	cin >> n >> m >> x >> y >> l >> r;
	for (int i = 1; i <= n; i++)
		scanf("%s", g[i] + 1);
	BFS();
	cout << ans << endl;

	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值