H - Open the Lock(bfs)

在这里插入图片描述

#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
struct node
{
    int a[4],step;
};
char str[2][5];
int f[4];
bool vis[10][10][10][10];//这里不能在这赋值为0,要在下面赋值
int BFS()//有返回值,用int
{
    node now,next;
    for(int i=0;i<4;i++)
    {
        now.a[i]=str[0][i]-'0';
        f[i]=str[1][i]-'0';
    }
    memset(vis,false,sizeof(vis));//在这里对标记初始化
    now.step=0;
    queue<node>q;
    q.push(now);
    bool lock;
 
    while(!q.empty())
    {
        now=q.front();
        q.pop();
        lock=true;
        for(int i=0;i<4;i++)
        {
            if(now.a[i]!=f[i])
            {
                lock=false;
                break;
            }
        }
        if(lock)
            return now.step;
        for(int i=0;i<4;i++)//加一
        {
            next=now;
            if(now.a[i]==9)
                next.a[i]=1;
            else
                next.a[i]=now.a[i]+1;
            if(!vis[next.a[0]][next.a[1]][next.a[2]][next.a[3]])
            {
                vis[next.a[0]][next.a[1]][next.a[2]][next.a[3]]=true;
                next.step=now.step+1;
                q.push(next);
            }
        }
        for(int i=0;i<4;i++)//减一
        {
            next=now;
            if(now.a[i]==1)
                next.a[i]=9;
            else
                next.a[i]=now.a[i]-1;
            if(!vis[next.a[0]][next.a[1]][next.a[2]][next.a[3]])
            {
                vis[next.a[0]][next.a[1]][next.a[2]][next.a[3]]=true;
                next.step=now.step+1;
                q.push(next);
            }
        }
        for(int i=0;i<3;i++)//交换
        {
            next=now;
            next.a[i]=now.a[i+1];
            next.a[i+1]=now.a[i];
            if(!vis[next.a[0]][next.a[1]][next.a[2]][next.a[3]])
            {
                vis[next.a[0]][next.a[1]][next.a[2]][next.a[3]]=true;
                next.step=now.step+1;
                q.push(next);
            }
        }
    }
    //return -1;要不要都行
}
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        cin>>str[0]>>str[1];
        cout<<BFS()<<endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值