【Leetcode】1036. 逃离大迷宫

题目:1036

题意:在一个 10^6 x 10^6 的网格中,每个网格块的坐标为 (x, y),其中 0 <= x, y < 10^6。我们从源方格 source 开始出发,意图赶往目标方格 target。每次移动,我们都可以走到网格中在四个方向上相邻的方格,只要该方格不在给出的封锁列表 blocked 上。只有在可以通过一系列的移动到达目标方格时才返回 true。否则,返回 false。

题解:由于题目中迷宫面积太大10^6 × 10^6 ,直接使用BFS肯定超时,所以不能直接使用BFS。但我们可以看到所给的障碍块比较少0-200,因此我们可以从障碍块出发,假设障碍块数量为n,则障碍块所能围成的最大面积为:maxstep = n*(n-1) / 2 ,即如果在步数 < maxstep 之内没有到达目标点,或者广度优先搜索完可行区域,即源点和目标点之间不可到达

代码:

class Solution {
private:
	int maxstep;
	int dx[4] = { 0, 0, 1, -1 };
	int dy[4] = { 1, -1, 0, 0 };
	int bound = 1000000;
public:
	bool BFS(set<pair<int, int> > s, vector<int>& source, vector<int>& target) {
		queue<pair<int, int> > q;
		q.push({ source[0], source[1] });
		s.insert({ source[0], source[1] });
		int step = 0;
		int x, y;
		while (!q.empty()) {
			step++;
			pair<int, int> p = q.front();
			q.pop();
			if ((p.first == target[0] && p.second == target[1]) || step > maxstep)return true;
			for (int i = 0; i < 4; ++i) {
				x = p.first + dx[i];
				y = p.second + dy[i];
				if (x >= 0 && x < bound && y >= 0 && y < bound && !s.count({ x,y }))
				{
					q.push({ x,y });
					s.insert({ x,y });
				}
					
			}
		}
		return false;
	}
	bool isEscapePossible(vector<vector<int>>& blocked, vector<int>& source, vector<int>& target) {
		set<pair<int, int> > s;
		int n = blocked.size();
		maxstep = n * (n - 1) / 2;
		for (int i = 0; i < n; ++i)
			s.insert({ blocked[i][0], blocked[i][1] });
		return BFS(s, source, target) && BFS(s, target, source);
	}
};

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值