连连看(hdu 1175)用队列实现广搜,并加入了动态规划

 http://acm.hdu.edu.cn/showproblem.php?pid=1175

 

一道ACM题目,方法很经典,源码如下:

 

#include<iostream>
#include<queue>
using namespace std;
int h[1005][1005];

int v[1005][1005];
int n,m,w,win;
struct node{int x,y,flag,step;};
queue <node> que;
node temp,tmp;
int mov[4][2]={{1,0},{0,1},{-1,0},{0,-1}};

int run(int a,int b,int c,int d)
{
    int i,x,y;
    memset(v,-1,sizeof(v));
    while(!que.empty())que.pop();
    for(i=0;i<4;i++){
    temp.x=a;
    temp.y=b;
    temp.flag=i;
    temp.step=0;
    que.push(temp);}
    while(!que.empty())
    {
        tmp=que.front();
        que.pop();

        for(i=0;i<4;i++)
        {
            x=tmp.x+mov[i][0];
            y=tmp.y+mov[i][1];
            if(x==c&&y==d)
            {
    if(i!=tmp.flag&&tmp.step>=2)continue;
                win=1;return 0;
            }
            if(h[x][y]==0&&x<=n&&x>=1&&y<=m&&y>=1)
            {
                if(i==tmp.flag&&(v[x][y]==-1||v[x][y]>=tmp.step))
                {
                    temp.x=x;
                    temp.y=y;
                    temp.step=tmp.step;
                    temp.flag=i;
                    v[x][y]=temp.step;
                    que.push(temp);
    }
                else if(tmp.step<2&&(v[x][y]==-1||v[x][y]>=tmp.step+1))
                {
                    temp.x=x;
                    temp.y=y;
                    temp.step=tmp.step+1;
                    temp.flag=i;
                    v[x][y]=temp.step;
                    que.push(temp);
                }
            }
        }
    }
return 0;
}
int main()
{
    int i,j,a,b,c,d;
    while(scanf("%d%d",&n,&m)&&n)
    {
        for(i=1;i<=n;i++)
            for(j=1;j<=m;j++)
            scanf("%d",&h[i][j]);
        scanf("%d",&w);
        while(w--)
        {
            win=0;
            scanf("%d%d%d%d",&a,&b,&c,&d);
            if(h[a][b]!=h[c][d]||h[a][b]==0||(a==c&&b==d)){printf("NO/n");continue;}
            run(a,b,c,d);
            if(win==1)printf("YES/n");
            else printf("NO/n");
        }
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值