Big Banned Grid
题目要求从左上角走到右下角。但是网格很大,全部遍历一遍非常不可行。
联想到小时候玩迷宫的经验,可以发现:如果可达的话,沿着墙走一定是对的。因此我们只需要关心墙边的格子就可以了。此处的“墙边”指所有墙八方向的格子以及边缘的所有格子。
只在这些被关心的格子中做 BFS。可以开一个 set 存下所有被关心的格子与被访问过的格子,每一步拓展的时候从 set 里检查。
#include <cstddef>
#include <iostream>
#include <queue>
#include <set>
#include <utility>
#include <vector>
using namespace std;
istream& fin = cin;
ostream& fout = cout;
using ui = unsigned int;
using uli = unsigned long long int;
using li = long long int;
int main(void) {
ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
size_t n, m, k;
fin >> n >> m >> k;
set<pair<ui, ui>> blk;
while (k--) {
ui x, y;
fin >> x >> y;
blk.emplace(--x, --y);
}
set<pair<ui, ui>> fav;
for (auto [x, y] : set(blk))
for (auto [nx, ny] :
{pair(x + 1, y), pair(x, y + 1), pair(x - 1, y), pair(x, y - 1),
pair(x + 1, y + 1), pair(x + 1, y - 1), pair(x - 1, y + 1),
pair(x - 1, y - 1)})
if (nx < n && ny < m)
fav.emplace(nx, ny);
for (size_t i = 0; i < n; ++i)
fav.emplace(i, 0), fav.emplace(i, m - 1);
for (size_t j = 0; j < m; ++j)
fav.emplace(0, j), fav.emplace(n - 1, j);
for (auto i : blk)
fav.erase(i);
set<pair<ui, ui>> vis;
vis.emplace(0, 0);
queue<pair<ui, ui>> q{{{0, 0}}};
while (!q.empty()) {
auto [x, y] = q.front();
q.pop();
for (auto [nx, ny] :
{pair(x + 1, y), pair(x, y + 1), pair(x - 1, y), pair(x, y - 1)})
if (fav.contains({nx, ny}) && vis.emplace(nx, ny).second)
q.emplace(nx, ny);
}
fout << (vis.contains({n - 1, m - 1}) ? "Yes\n" : "No\n");
return 0;
}