专栏文章
题解:AT_abc405_d [ABC405D] Escape Route
AT_abc405_d题解参与者 1已保存评论 0
文章操作
快速查看文章及其快照的属性,并进行相关操作。
- 当前评论
- 0 条
- 当前快照
- 1 份
- 快照标识符
- @mipb7j2s
- 此快照首次捕获于
- 2025/12/03 09:09 3 个月前
- 此快照最后确认于
- 2025/12/03 09:09 3 个月前
解法
首先,可以想到如果从每个点出发搜索到安全出口,其时间复杂度是远远不如从安全出口搜索到每个点的,并且两者的结果等价,不过是要将输出的方向反以下而已。
接下去我们可以发现这道题属于多源搜索,一般使用 BFS。接下去我们就可以发现只要在 BFS 过程中记录下到安全出口的距离,每次判断当前距离是否小于记录的距离,如果小于则更新距离和方向即可。
代码
CPP#include <bits/stdc++.h>
#define int long long
const int N = 1005;
const int Mod = 1e9 + 7;
using namespace std;
int n, m;
char a[N][N];
int dis[N][N];
int dx[4] = {0, -1, 0, 1};
int dy[4] = {1, 0, -1, 0};
char c[4] = {'<', 'v', '>', '^'};
struct node
{
int x, y, d;
};
signed main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
queue<node> q;
cin >> n >> m;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
dis[i][j] = 1e18;
cin >> a[i][j];
if (a[i][j] == 'E')
{
dis[i][j] = 0;
q.push({i, j, 0});
}
}
}
while (!q.empty())
{
auto [x, y, d] = q.front();
q.pop();
for (int i = 0; i < 4; i++)
{
int tx = x + dx[i];
int ty = y + dy[i];
if (tx < 1 || tx > n || ty < 1 || ty > m)
{
continue;
}
if (a[tx][ty] == '#')
{
continue;
}
if (d + 1 >= dis[tx][ty])
{
continue;
}
dis[tx][ty] = d + 1;
a[tx][ty] = c[i];
q.push({tx, ty, d + 1});
}
}
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
cout << a[i][j];
}
cout << endl;
}
return 0;
}
相关推荐
评论
共 0 条评论,欢迎与作者交流。
正在加载评论...