hdu1195Open the Lock(BFS)

题目链接:hdu1195

思路:BFS,对于每个数每次有11种操作,千位和百位交换,百位和十位交换,十位和个位交换,千位加一或减一,百位加一或减一,十位加一或减一,个位加一或减一,将每次操作得到的数与目标数进行对比,同时用数组v[]进行标记,已出现过的数不再压入队列中

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <string>
#include <queue>
using namespace std;

int num,v[10005];

struct node
{
    int num;
    int step;
};
void bfs(int t)
{
    int a[5];
    queue <node> q;
    node s,temp;
    s.num = t;
    s.step = 0;
    q.push(s);
    while(!q.empty())
    {
        temp = q.front();
        q.pop();
        a[0] = temp.num/1000;
        a[1] = (temp.num/100)%10;
        a[2] = (temp.num/10)%10;
        a[3] = temp.num%10;

        //交换千位和百位
        s.num = a[1]*1000 + a[0]*100 + a[2]*10 + a[3];
        s.step = temp.step + 1;
        if(s.num == num)
            {printf("%d\n",s.step); return ;}
        if(!v[s.num])
            {v[s.num] = 1; q.push(s);}

        //交换百位和十位
        s.num = a[0]*1000 + a[2]*100 + a[1]*10 + a[3];
        s.step = temp.step + 1;
        if(s.num == num)
            {printf("%d\n",s.step); return ;}
        if(!v[s.num])
            {v[s.num] = 1; q.push(s);}

        //交换十位和个位
        s.num = a[0]*1000 + a[1]*100+ a[3]*10 + a[2];
        s.step = temp.step + 1;
        if(s.num == num)
            {printf("%d\n",s.step); return ;}
        if(!v[s.num])
            {v[s.num] = 1; q.push(s);}

        for(int i = 0; i < 4; i ++)
        {
            int k = a[i];
            //加一
            if(a[i] == 9) {a[i] = 1; s.num = a[0]*1000 + a[1]*100 + a[2]*10 + a[3];}
            else {a[i] ++; s.num = a[0]*1000 + a[1]*100 + a[2]*10 + a[3];}
            s.step = temp.step + 1;
            if(s.num == num)
                {printf("%d\n",s.step);return ;}
            if(!v[s.num])
                {v[s.num] = 1;q.push(s);}

            a[i] = k;

            //减一
            if(a[i] == 1) {a[i] = 9; s.num = a[0]*1000 + a[1]*100 + a[2]*10 + a[3];}
            else {a[i] --; s.num = a[0]*1000 + a[1]*100 + a[2]*10 + a[3];}
            s.step = temp.step + 1;
            if(s.num == num)
                {printf("%d\n",s.step);return ;}
            if(!v[s.num])
                {v[s.num] = 1;q.push(s);}
            a[i] = k;
        }
    }
}
int main()
{
    int T,t;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d",&t,&num);
        memset(v,0,sizeof(v));
        bfs(t);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值