题目: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);
}
};