# HDU1195——Open the Lock (BFS)

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 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
9999
Sample Output
2
4
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>

using namespace std;

struct node
{
int num[4],step;
};

node start,_end;
bool visit[10][10][10][10],flag;

void bfs()
{
int i;
node p,q;
queue<node> Q; ///定义
memset(visit,false,sizeof(visit));///初始化
flag=true;
start.step=0;
p=start;
visit[p.num[0]][p.num[1]][p.num[2]][p.num[3]]=true;
Q.push(p);///从已有元素后面增加元素
while(!Q.empty())
{
p=Q.front();///第一个元素
Q.pop();///清除第一个元素

flag=true;
for(i=0; i<4; i++)
if(p.num[i]!=_end.num[i])
{
flag=false;
break;
};

if(flag)
{
printf("%d\n",p.step);
return;
}

for(i=0; i<4; i++) ///+1
{
q=p;
if(p.num[i]==9) q.num[i]=1;
else q.num[i]=p.num[i]+1;
q.step=p.step+1;
if(!visit[q.num[0]][q.num[1]][q.num[2]][q.num[3]])
{
visit[q.num[0]][q.num[1]][q.num[2]][q.num[3]]=true;
Q.push(q);
}
}
for(i=0; i<4; i++) ///-1
{
q=p;
if(p.num[i]==1) q.num[i]=9;
else q.num[i]=p.num[i]-1;
q.step=p.step+1;
if(!visit[q.num[0]][q.num[1]][q.num[2]][q.num[3]])
{
visit[q.num[0]][q.num[1]][q.num[2]][q.num[3]]=true;
Q.push(q);
}
}
for(i=0; i<3; i++) ///相邻交换
{
q=p;
q.num[i]=p.num[i+1];
q.num[i+1]=p.num[i];
q.step=p.step+1;
if(!visit[q.num[0]][q.num[1]][q.num[2]][q.num[3]])
{
visit[q.num[0]][q.num[1]][q.num[2]][q.num[3]]=true;
Q.push(q);
}
}
}
}

int main()
{
int n,i;
char chf[5],chl[5];
scanf("%d",&n);
while(n--)
{
scanf("%s%s",chf,chl);
for(i=0; i<4; i++)
{
start.num[i]=chf[i]-'0';
_end.num[i]=chl[i]-'0';
}
bfs();
}
return 0;
}