题目
解释
剪枝的搜索,BFS与DFS都可以
代码
//连连看
#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<math.h>
#include<queue>
using namespace std;
struct xjf{
int x, y, loststop, fan;
}now,well;
int dis[4][2] = { {0,1 }, { 0,-1 }, { 1,0 }, { -1,0 } };
int arr[1005][1005];
int endx,endy,n,m;
int DFS(xjf A) {
int flag[1005][1005] ;
memset(flag, 11, sizeof(flag));
queue <xjf> Q;
A.fan = 0;
A.loststop = 0;
Q.push(A);
while (!Q.empty()) {
now = Q.front();
Q.pop();
if (now.x == endx && now.y == endy && now.fan < 3) {
return 1;
}
if (now.fan < 3) {
for (int i = 0; i < 4; i++) {
int ix = now.x + dis[i][0];
int iy = now.y + dis[i][1];
if (ix >= 0 && iy >= 0 && ix < n && iy < m && (arr[ix][iy] == 0 || (ix == endx &&iy == endy))) {
well.x = ix;
well.y = iy;
well.fan = now.fan;
if (now.loststop == 0) well.loststop = dis[i][0] * 10 + dis[i][1];
else if (now.loststop == dis[i][0] * 10 + dis[i][1]) {
well.loststop = dis[i][0] * 10 + dis[i][1];
}
else if (now.loststop + dis[i][0] * 10 + dis[i][1]==0) {
continue;
}
else {
well.loststop = dis[i][0] * 10 + dis[i][1];
well.fan ++;
}
if (flag[ix][iy] > well.fan && well.fan <= 2){
flag[ix][iy] = well.fan;
Q.push(well);
}
}
}
}
}
return 0;
}
int main() {
while (cin >> n >> m) {
if (n == 0 && m == 0)
break;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> arr[i][j];
}
}
int t;
cin >> t;
while (t--) {
xjf A;
cin >> A.x >> A.y >> endx >> endy;
endx--;
endy--;
A.x--;
A.y--;
if ((A.x == endx && A.y == endy)||A.x<0||A.x>=n||A.y<0||A.y>=m || endx < 0 || endx >= n || endy < 0 || endy >= m) {
cout << "NO" << endl;
continue;
}
if (arr[A.x ][A.y ] == arr[endx ][endy]&& arr[A.x][A.y] != 0) {
if (DFS(A) == 1) cout << "YES" << endl;
else cout << "NO" << endl;
}
else {
cout << "NO" << endl;
}
}
}
return 0;
}