题目
#include<iostream>
using namespace std;
#include<string>
#include<queue>
int vis[10][10][10][10];
struct Node{
int num[4];
int step;
}first,last,node;
queue<Node> qq;
void bfs(Node node)
{
vis[node.num[0]][node.num[1]][node.num[2]][node.num[3]]=1;
qq.push(node);
while(!qq.empty())
{
Node no=qq.front();
qq.pop();
if(no.num[0]==last.num[0] && no.num[1]==last.num[1] && no.num[2]==last.num[2] && no.num[3]==last.num[3])
{
cout<<no.step;
break;
}
Node next;
for(int i=0;i<4;i++) //reduce 1
{
next=no;
next.step++;
next.num[i]=(next.num[i]+8)%9; // %altol means making a circle,+1 means after now,+altol means don't move ,+altol-1 means before now
if(!vis[next.num[0]][next.num[1]][next.num[2]][next.num[3]])
{
qq.push(next);
vis[next.num[0]][next.num[1]][next.num[2]][next.num[3]]=1;
}
}
for(int i=0;i<4;i++) //add 1
{
next=no;
next.step++;
next.num[i]=(next.num[i]+1)%9;
if(!vis[next.num[0]][next.num[1]][next.num[2]][next.num[3]])
{
qq.push(next);
vis[next.num[0]][next.num[1]][next.num[2]][next.num[3]]=1;
}
}
for(int j=0;j<3;j++) //exchange each other near
{
next=no;
next.step++;
int tt=next.num[j];
next.num[j]=next.num[j+1];
next.num[j+1]=tt;
if(!vis[next.num[0]][next.num[1]][next.num[2]][next.num[3]])
{
qq.push(next);
vis[next.num[0]][next.num[1]][next.num[2]][next.num[3]]=1;
}
}
}
}
int main()
{
string fir,las;
cin>>fir>>las;
for(int i=0;i<4;i++) //1-9 change to 0-8 in order to mod
{
node.num[i]=fir[i]-'0'-1;
first.num[i]=fir[i]-'0'-1;
last.num[i]=las[i]-'0'-1;
}
node.step=0;
bfs(node);
return 0;
}