HDU 1195 Open the Lock 简单搜索-bfs

题目地址: http://acm.hdu.edu.cn/showproblem.php?pid=1195

 

一个标准的宽搜,一点不需要剪枝

需要注意的一点是:交换的时候,这个地方只能交换邻居,我当时看错以为可以任意交换

 

 

代码如下:

#include <iostream>
#include <queue>
using namespace std;

int a[5],b[5];
bool visit[10010];
int hashb;

struct xh
{
    int d[5];
    int t;
}w,ww;

int hash(int x[])
{
    int i,sum=0;
    for(i=1;i<=4;i++)
        sum=sum*10+x[i];
    return sum;
}

int add(int n)
{
    if(n==9)
        return 1;
    return n+1;
}

int jian(int n)
{
    if(n==1)
        return 9;
    return n-1;
}

int bfs()
{
    int i,j,hashx;
    memset(visit,false,sizeof(visit));
    queue<xh>q;
    for(i=1;i<=4;i++)
        w.d[i]=a[i];
    w.t=0;
    hashx=hash(a);
    visit[hashx]=true;
    q.push(w);
    while(!q.empty())
    {
        ww=q.front();
        q.pop();
        if(hash(ww.d)==hashb)
        {
            printf("%d\n",ww.t);
            break;
        }
        //加一减一
        for(i=1;i<=4;i++)
        {
            w=ww;//加一
            w.d[i]=add(w.d[i]);
            hashx=hash(w.d);
            if(!visit[hashx])
            {
                visit[hashx]=true;
                w.t++;
                q.push(w);
            }

            w=ww;//减一
            w.d[i]=jian(w.d[i]);
            hashx=hash(w.d);
            if(!visit[hashx])
            {
                visit[hashx]=true;
                w.t++;
                q.push(w);
            }
        }
        //交换,这个地方只能交换邻居,我当时看错了题目
        for(i=1;i<4;i++)
        {
            w=ww;
            swap(w.d[i],w.d[i+1]);
            hashx=hash(w.d);
            if(!visit[hashx])
            {
                visit[hashx]=true;
                w.t++;
                q.push(w);
            }
        }
    }
}

int main()
{
    int i,j,n,T;
    char c;
    cin>>T;
    while(T--)
    {
        for(i=1;i<=4;i++)
        {
            cin>>c;
            a[i]=c-'0';
        }
        for(i=1;i<=4;i++)
        {
            cin>>c;
            b[i]=c-'0';
        }
        hashb=hash(b);
        bfs();
    }
    return 0;
}


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值