每次进行一次"彻底"的搜索.所谓彻底的搜索,就是一次性一条直线走过去,因为我们转了一个弯之后无论走多远都不会增加转弯数;
0 | 1 | 2 | 3 |
0 | 0 | 0 | 0 |
0 | 1 | 2 | 1 |
0 | 0 | 0 | 0 |
比如上面这个表格,我们从 (4,3) 1出来后往下,转弯数量为1(我们也记录一次转弯,最后判断转弯数不超过3而不是2)
到达(4,4) 再转个弯往左走,我们可以一直走到(4,1) 都算2个弯.这就是 一次 "彻底" 的搜索!
/*
*HDU 1175
*fuqiang11
*BFS
*2013/7/30
*关于转弯次数,本来第一次 出去不计入方向,但是我们计入进去,所以最终判断他不超过3个弯,而不是2个
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <cstdlib>
using namespace std;
#define maxn 1000+3
int map[maxn][maxn];
bool vis[maxn][maxn];
int xx[] = {0,0,1,-1};
int yy[] = {1,-1,0,0};
int n,m;
struct point
{
int x;
int y;
int turn;
};
bool check(int x, int y)
{
if(x<1||y<1||x>n||y>m||vis[x][y])
return false;
return true;
}
queue <point> q;
int BFS(point st, point ed)
{
memset(vis,false,sizeof(vis));
while(!q.empty())
q.pop();
st.turn = 0;
q.push(st);
vis[st.x][st.y] = true;
point a,b;
while(!q.empty())
{
a = q.front();
q.pop();
if(a.turn >= 3) //目前到达的点已经转了3个弯了.再转就超过了.
return 0;
for(int i = 0; i < 4; i++)
{
b.x = a.x + xx[i];
b.y = a.y + yy[i];
b.turn = a.turn + 1;
while(check(b.x, b.y) && map[b.x][b.y]==0)
{
q.push(b);
vis[b.x][b.y] = true;
b.x += xx[i];
b.y += yy[i];
}
if(check(b.x, b.y))
{
if(b.x == ed.x && b.y == ed.y) //能到达终点
{
if(b.turn <= 3)
return 1;
}
}
}
}
return 0;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("in","r",stdin);
#endif
int q;
point st,ed;
while(scanf("%d%d",&n,&m)&&(n+m))
{
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++)
scanf("%d",&map[i][j]);
scanf("%d",&q);
while(q--)
{
scanf("%d%d%d%d",&st.x,&st.y,&ed.x,&ed.y);
if(map[st.x][st.y] != map[ed.x][ed.y]) //连的块不一样,直接输出 NO
puts("NO");
else
if(BFS(st,ed)) //找到
puts("YES");
else
puts("NO");
}
}
}