题意:一个4位密码锁,每位数字处在1~9之间,每个位可以加一或减一,如果1减一,则变为9,如果9加一,则变为1.另外相邻两数字可以交换,但是最左与最右不算相邻。
思路:每进行一次位操作,都视为状态的转移,每个状态之访问一次,bfs:从最初的状态开始,不断向相邻状态扩展,每向相邻状态转移一次,步数加1,直到到达终点就是最短路径
#include<cstdio>
#include<cstring>
#include<queue>
#include<cmath>
using namespace std;
const int maxn = 10000;
int vis[maxn];
int n,m,step;
void bfs(int start,int end)
{
queue<int> q;
q.push(start);
vis[start]=1;
while(!q.empty())
{
int sz = q.size();
while(sz--)
{
int cur = q.front();q.pop();
if(cur==end)return;
int a[4],t;
a[3]=cur%10;
a[2]=(cur/10)%10;
a[1]=(cur/100)%10;
a[0]=cur/1000;
for(int i=0;i<4;i++)
{
int ch = a[i];
a[i]+=1;
if(a[i]>9)a[i]=1;
t=0;
for(int j=0;j<4;j++)
t = (t*10 + a[j]);
if(!vis[t])
{
q.push(t);
vis[t]=1;
}
a[i]=ch;
a[i]-=1;
if(a[i]<=0)a[i]=9;
t=0;
for(int j=0;j<4;j++)
t = (t*10 + a[j]);
if(!vis[t])
{
q.push(t);
vis[t]=1;
}
a[i]=ch;
}
t=a[3]+a[2]*10+a[0]*100+a[1]*1000;
if(!vis[t])
{
q.push(t);
vis[t]=1;
}
t=a[3]+a[1]*10+a[2]*100+a[0]*1000;
if(!vis[t])
{
q.push(t);
vis[t]=1;
}
t=a[2]+a[3]*10+a[1]*100+a[0]*1000;
if(!vis[t])
{
q.push(t);
vis[t]=1;
}
}
step++;
}
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
int a,b;
scanf("%d%d",&a,&b);
memset(vis,0,sizeof(vis));
step=0;
bfs(a,b);
printf("%d\n",step);
}
}