给定一个含 k 个障碍的 n*m 网格图。 要求统计所有 种“通过障碍的上下方式”中,每种方式的最短路径。
对于每个障碍:
- 若只能从上方通过,则将该障碍正上方的格子全设为障碍;
- 若只能从下方通过,则将该障碍正下方的格子全设为障碍。
然后对每种情况跑一遍 BFS。 时间复杂度 2^k。
虽是暴力,但实现简单、思路直观。 ———————————————— 版权声明:本文为CSDN博主「rkc1221」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/2301_79549137/article/details/154748807
#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
const int N = 1 << 9;
const int inf = INT_MAX / 2;
struct node {
int x, y;
} p[1 << 9];
int a[N][N], dis[N][N], vis[N][N], n, m;
int dx[4] = {1, -1, 0};
int dy[4] = {0, 0, 1};
int calc() {
queue <node> q;
for (int i = 1; i <= n; i++) {
dis[i][1] = 0;
vis[i][1] = 1;
q.push({i, 1});
}
while (!q.empty()) {
auto [x, y] = q.front();
q.pop();
vis[x][y] = 1;
for (int i = 0; i < 3; i++) {
int tx = x + dx[i];
int ty = y + dy[i];
if (tx >= 1 && tx <= n && ty <= m && a[tx][ty] == 0 && vis[tx][ty] == 0) {
dis[tx][ty] = dis[x][y] + 1;
vis[tx][ty] = 1;
q.push({tx, ty});
}
}
}
int ans = inf;
for (int i = 1; i <= n; i++) {
ans = min(ans, dis[i][m]);
}
if (ans == inf) return -1;
else return ans;
}
void solve() {
cin >> n >> m;
int k;
cin >> k;
for (int i = 0; i < k; i++) {
cin >> p[i].x >> p[i].y;
}
for (int s = 0; s < (1 << k); s++) {
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= m; j++) {
a[i][j] = 0;
dis[i][j] = inf;
vis[i][j] = 0;
}
}
for (int i = 0; i < k; i++) {
if (s & (1 << i)) {
for (int j = 1; j <= p[i].x; j++) {
a[j][p[i].y] = 1;
}
}
else {
for (int j = p[i].x; j <= n; j++) {
a[j][p[i].y] = 1;
}
}
}
int ans = calc();
cout << ans << " ";
}
cout << endl;
}
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int T = 1;
cin >> T;
while (T--) solve();
return 0;
}———————————————— 版权声明:本文为CSDN博主「rkc1221」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/2301_79549137/article/details/154748807