蓝桥杯每日一题1.4 2017省赛A组2.跳蚱蜢[八数码问题][BFS][map去重]

题目描述

如图所示: 有9只盘子,排成1个圆圈。其中8只盘子内装着8只蚱蜢,有一个是空盘。 
 
我们把这些蚱蜢顺时针编号为 1~8。每只蚱蜢都可以跳到相邻的空盘中,也可以再用点力,越过一个相邻的蚱蜢跳到空盘中。 
请你计算一下,如果要使得蚱蜢们的队形改为按照逆时针排列,并且保持空盘的位置不变(也就是1-8换位,2-7换位,...),至少要经过多少次跳跃? 

输出

输出一个整数表示答案

https://blog.csdn.net/weixin_43914593/article/details/112132315

看成空盘在跳,祭出一个建模大法:“化圆为线”! 把空盘看成0,那么有9个数字{0,1,2,3,4,5,6,7,8},一个圆圈上的9个数字,拉直成了一条线上的9个数字。

化为线之后,【int k=(j+9)%9;】线化为圆

现在即为八数码问题,由初始状态“012345678”转换为终止状态“087654321”

下图为状态的树

八数码问题用BFS来解决,BFS借助queue来完成

进行剪枝,标识已经出现过的状态,利用map进行去重 

去重过程:

m[s]=true;//map字典标识是否出现过,出现过为true,初始默认为false

if(!m[s])

{

           m[s]=true;

           q.push(node(s,c+1));

 }

highlight:

1.struct 结构构造函数的编写

struct node

{

    node(){}

    node(string ss,int cc)

    {

        s=ss;//!!!!!!

        c=cc;//!!!!!!!!!

    }

    string s;//!!!!!

    int c;//!!!!!

};

2.int k=(j+9)%9;边界处理

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<set>
#include<queue>
#include<stack>
#include<map>
using namespace std;
typedef long long ll;
const int maxn = 110000;

struct node
{
    node(){}
    node(string ss,int cc)
    {
        s=ss;//!!!!!!
        c=cc;//!!!!!!!!!
    }
    string s;//!!!!!
    int c;//!!!!!
};

queue<node>q;
map<string,bool>m;

void bfs()
{
    while(!q.empty())
    {
        node cur=q.front();
        q.pop();
        string s=cur.s;//!!!!
        int c=cur.c;//!!!
        if(s=="087654321")
        {
            cout<<c;
            break;
        }
        int i;
        for(i=0;i<10;i++)
        {
            if(s[i]=='0')
                break;
        }
        for(int j=i-2;j<=i+2;j++)
        {
            int k=(j+9)%9;
            if(k==i) continue;
            char t=s[i];
            s[i]=s[k];
            s[k]=t;
            if(!m[s])
            {
                m[s]=true;
                q.push(node(s,c+1));
            }
            t=s[i];
            s[i]=s[k];
            s[k]=t;
        }
    }
}

int main()
{
    string s="012345678";
    q.push(node(s,0));
    m[s]=true;
    bfs();
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值