Now an emergent task for you is to open a password lock. The password is consisted of four digits. Each digit is numbered from 1 to 9.
Each time, you can add or minus 1 to any digit. When add 1 to '9', the digit will change to be '1' and when minus 1 to '1', the digit will change to be '9'. You can also exchange the digit with its neighbor. Each action will take one step.
Now your task is to use minimal steps to open the lock.
Note: The leftmost digit is not the neighbor of the rightmost digit.
InputThe input file begins with an integer T, indicating the number of test cases.
Each time, you can add or minus 1 to any digit. When add 1 to '9', the digit will change to be '1' and when minus 1 to '1', the digit will change to be '9'. You can also exchange the digit with its neighbor. Each action will take one step.
Now your task is to use minimal steps to open the lock.
Note: The leftmost digit is not the neighbor of the rightmost digit.
Each test case begins with a four digit N, indicating the initial state of the password lock. Then followed a line with anotther four dight M, indicating the password which can open the lock. There is one blank line after each test case.
OutputFor each test case, print the minimal steps in one line.
Sample Input
2 1234 2144 1111 9999Sample Output
2 4
那第一个数字1234举例,它的执行过程是这样的:
1234
(+1) (-1) (交换)
step为1的数字 2234 9134 2134 1334 1134 1324 1244 1224 1243 1235 1232
step为2的数字 (在2234基础上每个位数+1 -1 交换)2234又可以出现一堆分支3234 1234(出现过)2234(出现过)等等
step为...的数字
如此进行下去,找到2144 输出其step。
#include<cstdio>
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
char s1[5],s2[5];
int mark[10][10][10][10];
struct node
{
char k[5];
int step;
};
int bfs()
{
int i;
memset(mark,0,sizeof(mark));
queue<node>m;
node first,next;
strcpy(first.k,s1);
first.step=0;
mark[s1[0]-'0'][s1[1]-'0'][s1[2]-'0'][s1[3]-'0']=1;
m.push(first);
while(!m.empty())
{
first=m.front();
m.pop();
if(strcmp(first.k,s2)==0)
return first.step;
for(i=0;i<4;i++)
{
strcpy(next.k,first.k);
if(next.k[i]=='9')
next.k[i]='1';
else
next.k[i]+=1;
next.step=first.step+1;
while(!mark[next.k[0]-'0'][next.k[1]-'0'][next.k[2]-'0'][next.k[3]-'0'])
{
mark[next.k[0]-'0'][next.k[1]-'0'][next.k[2]-'0'][next.k[3]-'0']=1;
m.push(next);
}
strcpy(next.k,first.k);
if(next.k[i]=='1')
next.k[i]='9';
else
next.k[i]-=1;
next.step=first.step+1;
while(!mark[next.k[0]-'0'][next.k[1]-'0'][next.k[2]-'0'][next.k[3]-'0'])
{
mark[next.k[0]-'0'][next.k[1]-'0'][next.k[2]-'0'][next.k[3]-'0']=1;
m.push(next);
}
if(i<3)
{
strcpy(next.k,first.k);
next.k[i]=first.k[i+1];
next.k[i+1]=first.k[i];
next.step=first.step+1;
while(!mark[next.k[0]-'0'][next.k[1]-'0'][next.k[2]-'0'][next.k[3]-'0'])
{
mark[next.k[0]-'0'][next.k[1]-'0'][next.k[2]-'0'][next.k[3]-'0']=1;
m.push(next);
}
}
}
}
return -1;
}
int main()
{
int t;
while(scanf("%d",&t)!=EOF)
{
while(t--)
{
scanf("%s%s",s1,s2);
printf("%d\n",bfs());
}
}
return 0;
}