題意: 現有一個n * m 的迷宮,期間 '#'表示牆壁, '.'表示道路 , 'G’表示好人, 'B’表示壞人。試問是否能通過將某些道路改建爲牆壁,以使所有壞人不能從(n,m)出口逃出,而所有好人可以。
思路: 這題看似很複雜,其實是有規律的。
- 爲了避免影響好人的逃生,應該在壞人的四周建立圍牆
- 爲了降低時間複雜度,應該以(n,m)爲起點開始bfs(),標記所有能到達的點。最後遍歷所以格點,若有好人未被標記就是"NO",反之"YES"。
代碼實現:
#include<bits/stdc++.h>
#define endl '\n'
#define null NULL
#define ll long long
#define pii pair<int, int>
#define lowbit(x) (x &(-x))
#define ls(x) x<<1
#define rs(x) (x<<1+1)
#define me(ar) memset(ar, 0, sizeof ar)
#define mem(ar,num) memset(ar, num, sizeof ar)
#define rp(i, n) for(int i = 0, i < n; i ++)
#define rep(i, a, n) for(int i = a; i <= n; i ++)
#define pre(i, n, a) for(int i = n; i >= a; i --)
#define IOS ios::sync_with_stdio(0); cin.tie(0);cout.tie(0);
const int way[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
using namespace std;
const int inf = 0x7fffffff;
const double PI = acos(-1.0);
const double eps = 1e-6;
const ll mod = 1e9 + 7;
const int N = 2e5 + 5;
int t, n, m, ok;
char mp[55][55];
bool vis[55][55];
struct node{
int x, y;
};
void add(int x, int y)
{
for(int i = 0; i < 4; i ++){
int nx = x + way[i][0];
int ny = y + way[i][1];
if(nx > 0 && nx <= n && ny > 0 && ny <= m){
if(mp[nx][ny] == 'G') ok = 0;
if(mp[nx][ny] == '.') mp[nx][ny] = '#';
}
}
}
//常規bfs操作
void bfs(int n, int m)
{
queue<node> q;
vis[n][m] = 1;
q.push((node){n, m});
while(!q.empty()){
node u = q.front(); q.pop();
for(int i = 0; i < 4; i ++){
int nx = u.x + way[i][0];
int ny = u.y + way[i][1];
if(nx > 0 && nx <= n && ny > 0 && ny <= m && !vis[nx][ny] && mp[nx][ny] != '#'){
vis[nx][ny] = 1;
q.push((node){nx, ny});
}
}
}
}
signed main()
{
IOS;
cin >> t;
while(t --){
ok = 1;
//切記要在主函數內初始化vis數組,否則若出口(n, m)爲牆壁時不會進行bfs操作,上一組的vis數組數據就會影響這組的測試
me(vis);
cin >> n >> m;
for(int i = 1; i <= n; i ++)
for(int j = 1; j <= m; j ++)
cin >> mp[i][j];
//在壞人的周圍修建牆壁
for(int i = 1; i <= n; i ++)
for(int j = 1; j <= m; j ++)
if(mp[i][j] == 'B') add(i, j);
if(mp[n][m] != '#') bfs(n, m);
//遍歷判斷是否有無法逃生的好人
for(int i = 1; i <= n; i ++){
for(int j = 1; j <= m; j ++)
if(mp[i][j] == 'G' && !vis[i][j])
{ok = 0; break;}
if(!ok) break;
}
if(ok) cout << "YES" << endl;
else cout << "NO" << endl;
}
return 0;
}