//多个k:经过K的最短路 = 起点开始到k + 终点开始到k 的最短路之和最小
#include <bits/stdc++.h>
using namespace std;
int n, m;
char M[500][500], m1[500][500], m2[500][500];
int D[500][500], d1[500][500], d2[500][500];
int dirx[4] = {0, -1, 0, 1};
int diry[4] = { -1, 0, 1, 0};
struct weizhi
{int x, y;
} s, e;
queue<weizhi>sq, eq;
int main()
{int T;cin >> T;while ( T-- ){cin >> n >> m;for ( int i = 0; i < n; i++ )for ( int j = 0; j < m; j++ ){cin >> M[i][j];m1[i][j] = M[i][j], m2[i][j] = M[i][j];d1[i][j] = 1e9, d2[i][j] = 1e9, D[i][j] = 1e9;if ( M[i][j] == 'P' ) s.x = i, s.y = j, sq.push ( s );if ( M[i][j] == 'E' ) e.x = i, e.y = j, eq.push ( e );} //复制两张相同的地图void sbfs ( weizhi );sbfs ( s ); //从起点开始广搜void ebfs ( weizhi );ebfs ( e ); //从终点开始int ans = 1e9;for ( int i = 0; i < n; i++ )for ( int j = 0; j < m; j++ ){if ( M[i][j] == 'K' )D[i][j] = d1[i][j] + d2[i][j];//总距离=起点到k + 终点到k ans = ( ans < D[i][j] ) ? ans : D[i][j];}if ( ans == 1e9 ) cout << "No solution" << endl;else cout << ans << endl;}return 0;
}
void sbfs ( weizhi s )
{d1[s.x][s.y] = 0;m1[s.x][s.y] = '#';while ( !sq.empty() ){weizhi now = sq.front();sq.pop();weizhi t;for ( int i = 0; i < 4; i++ ){t.x = now.x + dirx[i];t.y = now.y + diry[i];if ( t.x >= 0 && t.x < n && t.y >= 0 && t.y < m&& m1[t.x][t.y] != '#' && m1[t.x][t.y] != 'E' ){ //不能进入出口所在的格子m1[t.x][t.y] = '#';d1[t.x][t.y] = d1[now.x][now.y] + 1;sq.push ( t );}}}
}
void ebfs ( weizhi e )
{d2[e.x][e.y] = 0;m2[e.x][e.y] = '#';while ( !eq.empty() ){weizhi now = eq.front();eq.pop();weizhi t;for ( int i = 0; i < 4; i++ ){t.x = now.x + dirx[i];t.y = now.y + diry[i];if ( t.x >= 0 && t.x < n && t.y >= 0 && t.y < m&& m2[t.x][t.y] != '#' ){m2[t.x][t.y] = '#';d2[t.x][t.y] = d2[now.x][now.y] + 1;eq.push ( t );}}}
}
本文发布于:2024-02-04 23:31:40,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170718883860758.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |