码题集OJ-地狱尖兵 (matiji.net)
#include<bits/stdc++.h>
using namespace std;
const int N = 510;
char g[N][N];
typedef pair<int, int> PII;
#define x first
#define y second
int dist1[N][N];
int dist2[N][N];
int cnt1, cnt2;
int n, m;
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
void bfs2(int tx,int ty) {
queue<PII> q;
q.push({tx,ty});
dist2[tx][ty] = 0;
while (q.size()) {
PII t = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
int x = t.x + dx[i], y = t.y + dy[i];
if (x >= 0 && x < n && y >= 0 && y < m && dist2[x][y] == -1 && g[x][y] != '#') {
dist2[x][y] = dist2[t.x][t.y] + 1;
q.push({x, y});
if (g[x][y] == 'E') {
cnt2 += dist2[x][y];
return;
}
}
}
}
}
void bfs1(int x,int y) {
queue<PII> q;
q.push({x,y});
dist1[x][y] = 0;
while (q.size()) {
PII t = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
int tx = t.x + dx[i], ty = t.y + dy[i];
if (tx >= 0 && tx < n && ty >= 0 && ty < m && dist1[tx][ty] == -1 && g[tx][ty] != '#' && g[tx][ty] != 'E') {
dist1[tx][ty] = dist1[t.x][t.y] + 1;
q.push({tx, ty});
if (g[tx][ty] == 'K') {
cnt1 = dist1[tx][ty];
bfs2(tx, ty);
return;
}
}
}
}
}
int main() {
int t;
cin >> t;
while (t--) {
memset(dist1, -1, sizeof dist1);
memset(dist2, -1, sizeof dist2);
cnt1 = 0, cnt2 = 0;
cin >> n >> m;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cin >> g[i][j];
int x,y;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (g[i][j] == 'P')
x=i,y=j;
bfs1(x,y);
if (cnt1 && cnt2)
cout << cnt1 + cnt2 << endl;
else
cout << "No solution" << endl;
}
return 0;
}
