ABC405D 做题记录
N1tr0us_Acid · · 个人记录
有的人赛时调 bfs 调了30分钟。
\texttt{Solution}
思路比较一眼。我们先记录下每个紧急出口的位置,然后以每个紧急出口为遍历起点,用 bfs 求出每个点与最近的紧急出口的距离。
void bfs() {
queue <node> q;
memset(vis, 0x3f3f3f3f, sizeof(vis));
for (auto u : pos) {
q.push({u.first, u.second, 0});
}
while (q.size()) {
auto u = q.front();
q.pop();
int nx = u.x, ny = u.y, nstep = u.step;
if(nx < 1 || ny < 1 || nx > h || ny > w) continue;
if(nstep >= vis[nx][ny]) continue;
if(ans[nx][ny] == '#') continue;
vis[nx][ny] = nstep;
for (int i = 0; i < 4; i ++) {
int tox = dx[i] + nx, toy = dy[i] + ny;
q.push({tox, toy, nstep + 1});
}
}
}
然后我们发现,这个题要求方向。这个方向怎么求?
我们尝试着去观察
在第一组样例下,
3 2 1 0
4 i 2 1
5 4 3 2
其中 i 表示无法到达。
举个例子,第一行第一个数和第二个数分别是
欸!方向不就求出来了!如果一个点的上下左右有某个点的
\texttt{Final Code}
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int N = 1005;
char c[N][N], ans[N][N];
int h, w;
typedef pair <int, int> pii;
vector <pii> pos;
int vis[N][N];
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};
string alp = "^v<>"; // 方向
struct node {
int x, y, step;
};
void bfs() {
queue <node> q;
memset(vis, 0x3f3f3f3f, sizeof(vis));
for (auto u : pos) {
q.push({u.first, u.second, 0});
}
while (q.size()) {
auto u = q.front();
q.pop();
int nx = u.x, ny = u.y, nstep = u.step;
if(nx < 1 || ny < 1 || nx > h || ny > w) continue;
if(nstep >= vis[nx][ny]) continue;
if(ans[nx][ny] == '#') continue;
vis[nx][ny] = nstep;
for (int i = 0; i < 4; i ++) {
int tox = dx[i] + nx, toy = dy[i] + ny;
q.push({tox, toy, nstep + 1});
}
}
}
signed main() {
cin >> h >> w;
for (int i = 1; i <= h; i ++) {
for (int j = 1; j <= w; j ++) {
cin >> c[i][j];
ans[i][j] = '?';
if(c[i][j] == '#') ans[i][j] = c[i][j];
if(c[i][j] == 'E') {
ans[i][j] = c[i][j];
pos.push_back({i, j});
}
}
}
bfs();
for (int i = 1; i <= h; i ++) {
for (int j = 1; j <= w; j ++) {
int now = vis[i][j];
if(ans[i][j] != '?') {
continue;
}
for (int k = 0; k < 4; k ++) {
int tox = i + dx[k], toy = j + dy[k];
if(tox < 1 || toy < 1 || tox > h || toy > w) {
continue;
}
if(now - 1 == vis[tox][toy]) {
ans[i][j] = alp[k];
break;
}
}
}
}
for (int i = 1; i <= h; i ++) {
for (int j = 1; j <= w; j ++) cout << ans[i][j];
puts("");
}
return 0;
}