hdu1175 bfs

// hdu 1175
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
struct node
{
    int x , y ;
    int step ;
}s,e;
node qu[1100000];
int dir[4][2] = {{-1,0},{0,1},{1,0},{0,-1}};
int n , m , bx ,by ,ex ,ey;
int map[1001][1000];
bool f[1001][1000];
bool flag;
bool is_ok(int x, int y)
{
    if( x >=1 && x <= n && y >= 1 && y<= m )
        return true;
    return false;
}
void bfs()
{
    int head = 0 , tail = 1;
    s.x = bx ; s.y = by ; s.step = -1;
    qu[0] = s;
    f[bx][by] = true;
    while(head < tail)
    {
        s = qu[head++];
        int i;
        for(i=0;i<4;i++)
        {
            e.x = s.x + dir[i][0];
            e.y = s.y + dir[i][1];
            e.step = s.step + 1;
        //  cout<<"s.step is: "<<s.step<<" e.step is:"<<e.step<<endl;
        //  cout<<"s index:"<<s.x<<" "<<s.y<<endl;
        //  cout<<"e index:"<<e.x<<" "<<e.y<<endl;
            while( is_ok(e.x , e.y) && ( !map[e.x][e.y] ||( e.x == ex && e.y == ey)) )
            {
                if( !f[e.x][e.y] )
                {
                    f[e.x][e.y] = true;
                    qu[tail++] = e;
                    if( e.x == ex && e.y == ey && e.step <= 2)
                    {
                        flag = true;
                        return ;
                    }
                }
                e.x += dir[i][0];
                e.y += dir[i][1];
                e.step = s.step + 1;
            }
        }
    }
    return;
}
int main()
{
  //  freopen("1.txt","r",stdin);
    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]);
        int k;
        scanf("%d",&k);
        for(int i=0;i<k;i++)
        {
            scanf("%d %d %d %d", &bx ,&by , &ex ,&ey);
            if( map[bx][by] != map[ex][ey] ||  map[bx][by]==0 ||map[ex][ey]==0)
                cout << "NO" << endl;
            else
            {
                memset( f, false , sizeof(f));
                flag = false;
                bfs();
                if( flag ) cout << "YES" << endl;
                else       cout << "NO" << endl;
            }
        }
    }
    return 0;

}

  

posted @ 2013-07-26 16:10  JKXQJ  阅读(269)  评论(0编辑  收藏  举报