题目描述
如图所示: 有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;
}