题目就不多说了,主要分享一种回溯写法
blablabla
样例
blablabla
Code:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
char mp[101][101];
int T , n ;
int dx , dy , rx , ry;
int u[4] = {0 , 0 , 1 , -1} , v[4] = {1 , -1 , 0 , 0};
bool fl[101][101];
bool DFS(int x , int y){
for(int i = 0 ; i< 4 ; i++){
if(x == rx && y == ry) return true;
int x1 = x + u[i] , y1 = y + v[i];
if(x1 >= 0 && x1 < n && y1 >= 0 && y1 < n){
if(mp[x1][y1] == '.' && fl[x1][y1] == false){
fl[x1][y1] = true;
if(DFS(x1 , y1)) return true;
}
}
}
return false;
}
int main(){
cin >> T;
while(T--){
cin >> n;
for(int i = 0 ; i < n ; i++)
scanf("%s" , mp[i]);
cin >> dx >> dy >> rx >> ry;
memset(fl , false , sizeof(fl));
if(mp[dx][dy] == '#' || mp[rx][ry] == '#'){
cout << "NO" << endl;
continue;
}
if(DFS(dx , dy)) cout << "YES" << endl;
else cout << "NO" << endl;
}
return 0;
}
解释一下
没搜到返回’false’,搜到就一直true回去