AcWing 1112. 迷宫
虽然是DFS题,但是BFS也能写,看了一下y总的代码,思路差不多,就记录自己写的BFS版本了
#include<bits/stdc++.h>
using namespace std;
const int N = 105;
#define x first
#define y second
typedef pair<int, int>PII;
int n, k;
char g[N][N];
int ha, la, hb, lb;
bool st[N][N];
int dx[4] = {1, -1, 0, 0};
int dy[4] = {0, 0, 1, -1};
queue<PII>q;
bool dfs(){
//初始化
memset(st, 0, sizeof st);
while(q.size()) q.pop();
memset(g, 0, sizeof g);
cin>>n;
for(int i = 0; i < n; i ++ ){
for(int j = 0; j < n; j ++ ){
cin>>g[i][j];
}
}
cin>>ha>>la>>hb>>lb;
if(g[ha][la] == '#' || g[hb][lb] == '#') return false;
if(ha == hb && la == lb) return true;
q.push({ha, la});
st[ha][la] = true;
while(q.size()){
int xx = q.front().x;
int yy = q.front().y;
// cout<<xx<<' '<<yy<<endl;
q.pop();
for(int i = 0; i < 4; i ++ ){
int xxx = xx + dx[i];
int yyy = yy + dy[i];
if(xxx < 0 || yyy < 0) continue;
if(xxx < n && yyy < n && xxx >= 0 && yyy >= 0 && !st[xxx][yyy] && g[xxx][yyy] != '#'){
if(xxx == hb && yyy == lb) return true;
q.push({xxx, yyy});
st[xxx][yyy] = true;
}
}
}
return false;
}
int main()
{
cin>>k;
while(k -- ){
if(dfs()) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
return 0;
}