#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
int n,m;
int graph[1005][1005];
bool vis[1005][1005];
int x1,y1,x2,y2;
bool flag;
void dfs(int x,int y,int dir,int turn){ //1 2 3 4 上下左右
if(flag) return;
if(turn==3) return;
if(x<=0 || y<=0 || x>n || y>m) return;
if(x==x2 && y==y2){
flag = true;
return ;
}
if(turn==2){ //若当前已经达到最大的转弯次数,而到达终点仍然需要转弯
if(!((dir==1 && y==y2 && x>x2) || (dir=2 && y==y2 && x<x2) || (dir==3 && x==x2 && y>y2) || (dir==4 && x==x2 && y<y2) ))
return;
}
if(graph[x][y]!=0) return; //此处非空,不能经过
if(vis[x][y]) return;
vis[x][y] = 1;
if(dir==1){
dfs(x-1,y,1,turn);
dfs(x+1,y,2,turn+1);
dfs(x,y-1,3,turn+1);
dfs(x,y+1,4,turn+1);
}
else if(dir==2){
dfs(x-1,y,1,turn+1);
dfs(x+1,y,2,turn);
dfs(x,y-1,3,turn+1);
dfs(x,y+1,4,turn+1);
}
else if(dir==3){
dfs(x-1,y,1,turn+1);
dfs(x+1,y,2,turn+1);
dfs(x,y-1,3,turn);
dfs(x,y+1,4,turn+1);
}
else if(dir==4){
dfs(x-1,y,1,turn+1);
dfs(x+1,y,2,turn+1);
dfs(x,y-1,3,turn+1);
dfs(x,y+1,4,turn);
}
vis[x][y] = 0; //回溯
}
int main(){
while(scanf("%d%d",&n,&m)){
if(n==0 && m==0) break;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
scanf("%d",&graph[i][j]);
}
}
int q;
scanf("%d",&q);
while(q--){
memset(vis,false,sizeof(vis)); //每次查询都需要重置
scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
if(x1==x2 && y1==y2 && graph[x1][y1]!=0)
printf("NO\n");
else if(graph[x1][y1]==graph[x2][y2] && graph[x1][y1]!=0){
flag = 0;
dfs(x1-1,y1,1,0);
dfs(x1+1,y1,2,0);
dfs(x1,y1-1,3,0);
dfs(x1,y1+1,4,0);
if(flag)
printf("YES\n");
else
printf("NO\n");
}
else
printf("NO\n");
}
}
return 0;
}
HDU 1175 连连看 dfs
最新推荐文章于 2022-04-14 08:28:47 发布