hdu 1175 bfs+剪枝

来源:互联网 发布:奥维互动地图mac版 编辑:程序博客网 时间:2024/04/27 23:58
#include<iostream>#include<cstdio>#include<cstring>#include<queue>using namespace std;int a[1005][1005],n,m,flag,cnt[1005][1005];struct node{int sx,sy,hehe,cntxxx;}s,e;int temp[5][2]={0,0,0,1,1,0,0,-1,-1,0};void bfs(){    queue<node> que;    que.push(s);cnt[s.sx][s.sy]=0;    while(que.size())    {        node now=que.front();        que.pop();if(now.cntxxx>2)continue;        if(now.sx==e.sx&&now.sy==e.sy)        {            flag=1;            return;        }        for(int i=1;i<=4;i++)        {            int xx=now.sx+temp[i][0],yy=now.sy+temp[i][1];if(!(xx>0&&xx<=n&&yy>0&&yy<=m)) continue;            if(a[xx][yy]==0||((xx==e.sx)&&(yy==e.sy)))            {                node tp=now;                tp.sx=xx;                tp.sy=yy;                tp.hehe=i;                if(now.hehe!=i)                {                    if(now.hehe!=-1)tp.cntxxx++;                    if(tp.cntxxx==2&&((xx-e.sx)*temp[i][1]==(yy-e.sy)*temp[i][0]))                    {                        if(cnt[xx][yy]==-1||tp.cntxxx<cnt[xx][yy]){que.push(tp);cnt[xx][yy]=tp.cntxxx;}                    }                    else if(tp.cntxxx==1)                    {   if(cnt[xx][yy]==-1||tp.cntxxx<cnt[xx][yy])   {   que.push(tp);   cnt[xx][yy]=tp.cntxxx;   }}                }                if(cnt[xx][yy]==-1||tp.cntxxx<cnt[xx][yy]){que.push(tp);cnt[xx][yy]=tp.cntxxx;}            }        }    }}int main(){    int q;    while(scanf("%d%d",&n,&m)!=EOF&&(n||m))    {        for(int i=1;i<=n;i++)            for(int j=1;j<=m;j++)                scanf("%d",&a[i][j]);        scanf("%d",&q);        while(q--&&scanf("%d%d%d%d",&s.sx,&s.sy,&e.sx,&e.sy)!=EOF)        {            flag=0;            memset(cnt,-1,sizeof(cnt));s.cntxxx=0;s.hehe=-1;e.cntxxx=0;e.hehe=-1;            if(a[s.sx][s.sy]==a[e.sx][e.sy]&&a[s.sx][s.sy])                bfs();            if(flag)                printf("YES\n");            else                printf("NO\n");        }    }    return 0;}/*5 41 0 2 20 0 0 20 2 1 10 2 2 00 0 0 011 1 3 4*/

0 0
原创粉丝点击