知识点:枚举,最短路
这个题就跟刚刚做的做的题基本上一样了,一样是图论的最短路问题,就是找一个点到3个点的最短路径,唯一的不同是这个题我们要在外面补一圈空地,感觉这个也是比上个题难的地方,然后方法是双端队列BFS预处理+枚举,枚举每个点的时候,我们要注意的是枚举到那些是门的点,也就是边里面两个端点至少有一个这样的点边权就为1的点,当枚举到的时候最短距离要减2,因为3个重合了,那么就是减2,这样这个题就完成了,这种题难点还是怎么提炼图论的模型,抽象出来问题
#include <bits/stdc++.h>
using namespace std;
const int N = 105;
struct node {
int x, y, step;
node() {}
node(int a, int b, int c): x(a), y(b), step(c) {}
};
int n, m, d[4][N][N], vis[N][N];
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};
char s[N][N];
void bfs(int x) {
memset(vis, 0, sizeof(vis));
deque<node> q;
for (int i = 0; i <= n + 1; i++) {
for (int j = 0; j <= m + 1; j++) {
if (s[i][j] - '0' == x) q.push_back(node(i, j, 0));
}
}
while (!q.empty()) {
node now = q.front(); q.pop_front();
if (vis[now.x][now.y]) continue;
vis[now.x][now.y] = 1;
d[x][now.x][now.y] = now.step;
for (int i = 0; i < 4; i++) {
int x1 = now.x + dx[i];
int y1 = now.y + dy[i];
if (x1 < 0 || x1 > n + 1 || y1 < 0 || y1 > m + 1) continue;
if (s[x1][y1] == '*') continue;
if (s[x1][y1] != '#') q.push_front(node(x1, y1, now.step));
else q.push_back(node(x1, y1, now.step + 1));
}
}
}
int main() {
int T;
cin >> T;
while (T--) {
cin >> n >> m;
int cnt = 0;
for (int i = 1; i <= n; i++) {
scanf("%s", s[i] + 1);
for (int j = 1; j <= m; j++) {
if (s[i][j] == '$') s[i][j] = ++cnt + '0';
}
}
for (int i = 0; i <= n + 1; i++) {
s[i][0] = s[i][m + 1] = '3';
}
for (int i = 1; i <= m; i++) {
s[0][i] = s[n + 1][i] = '3';
}
for (int i = 0; i <= n + 1; i++) {
for (int j = 0; j <= m + 1; j++) {
d[1][i][j] = d[2][i][j] = d[3][i][j] = 1e8;
}
}
for (int i = 1; i <= 3; i++) {
bfs(i);
}
int ans = 1e9;
for (int i = 0; i <= n + 1; i++) {
for (int j = 0; j <= m + 1; j++) {
if (s[i][j] == '*') continue;
int tmp = d[1][i][j] + d[2][i][j] + d[3][i][j];
if (s[i][j] == '#') tmp -= 2;
ans = min(ans, tmp);
}
}
cout << ans << '\n';
}
return 0;
}