#include<stdio.h>
#include<iostream>
#include<queue>
#include<string.h>
using namespace std;
const double eps = 1e-8;
const int INF = 0x3f3f3f3f;
const int maxn = 5e2 + 5;
int G[maxn][maxn];
int v[maxn][maxn];
int k[maxn][maxn];
int px, py, ex, ey;
int ans;
int n, m;
int d[5][2] =
{0, 0,-1, 0,1, 0,0,-1,0, 1,
};
struct node
{int x, y, step;
};
bool judge(int x, int y)
{if (x < 0 || x >= n || y < 0 || y >= m || G[x][y] == 0 || v[x][y])return false;return true;
}
void bfs(int x, int y, int flag)
{memset(v,0,sizeof(v));queue <node> q;node tmp;tmp.x = x;tmp.y = y;tmp.step = 0;q.push(tmp);v[tmp.x][tmp.y] = 1;while (!q.empty()){node u = q.front(), w;q.pop();if (G[u.x][u.y] == 2){if (flag){if (k[u.x][u.y] != -1)ans = min(ans, k[u.x][u.y] + u.step);}else{k[u.x][u.y] = u.step;}}for (int i = 1; i < 5; i++){w.x = u.x + d[i][0];w.y = u.y + d[i][1];w.step = u.step + 1;if (judge(w.x, w.y)){q.push(w);v[w.x][w.y] = 1;}}}
}
int main()
{int t;cin >> t;while (t--){scanf("%d%d", &n, &m);char c;memset(k,-1,sizeof(k));for (int i = 0; i < n; i++){for (int j = 0; j < m; j++){scanf(" %c", &c);if (c == '#')G[i][j] = 0;else{G[i][j] = 1;if (c == 'P')px = i, py = j;else if (c == 'E')ex = i, ey = j;else if (c == 'K')G[i][j] = 2;}}}ans = INF;G[ex][ey] = 0;bfs(px, py, 0);G[ex][ey] = 1;bfs(ex, ey, 1);if (ans == INF)printf("No solutionn");elsecout << ans << endl;}
}
本文发布于:2024-02-04 23:30:53,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170718866060752.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |