Title description
As shown in the picture: There are 9 plates arranged in a circle. Eight of the plates contained eight grasshoppers, and one of them was empty.
We number these grasshoppers clockwise from 1 to 8. Each grasshopper can jump into the adjacent empty plate, or with a little more effort, jump over an adjacent grasshopper into the empty plate.
Please calculate, if you want to make the grasshoppers arranged in a counterclockwise order, and keep the position of the empty plate unchanged (that is, 1-8 transposition, 2-7 transposition,...), at least How many jumps have passed?
Output
Output an integer to indicate the answer
https://blog.csdn.net/weixin_43914593/article/details/112132315
Seeing that the empty disk is jumping, I offer a modeling method: " turn a circle into a line "! Taking the empty disk as 0, then there are 9 numbers {0,1,2,3,4,5,6,7,8}, 9 numbers on a circle, straightened to 9 on a line digital.
After turning into a line, [int k=(j+9)%9;] turning into a circle
Now it is the eight-digit problem, which has changed from the initial state "012345678" to the end state "087654321"
The picture below shows the state tree
Eight digital problems are solved by BFS, and BFS is completed by queue
Perform pruning, identify the state that has already appeared, and use map for deduplication
Deduplication process:
m[s]= true ;// Whether the map dictionary identifier has appeared, it is true when it appears, and the initial default is false
if(!m[s])
{
m[s]=true;
q.push(node(s,c+1));
}
highlight:
1. The writing of struct structure constructor
struct node
{
node(){}
node(string ss,int cc)
{
s=ss;//!!!!!!
c=cc;//!!!!!!!!!
}
string s;//!!!!!
int c;//!!!!!
};
2. int k=(j+9)%9; boundary processing
#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;
}