Open the Lock
Description
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.Input
The input file begins with an integer T, indicating the number of test cases.Output
For each test case, print the minimal steps in one line.Sample Input
2 1234 2144 1111 9999
Sample Output
2 4
#include#include #include using namespace std; struct node { int a; int t; }; int s,e; int toDigit(int a[]) { int ans=0; for(int i=0;i<4;i++) ans=ans*10+a[i]; return ans; } void toSprit(int a[],int ans) { int i=4; while(i>0) { a[--i]=ans%10; ans/=10; } } int bfs() { queue q; node p,tp; int vist[10000]={0},a[6]; if(s==e) return 0; p.a=s; p.t=0; q.push(p); vist[s]=1; while(!q.empty()) { p=q.front(); q.pop(); toSprit(a,p.a); tp.t=p.t+1; for(int i=0;i<4;i++) { if(a[i]==9) a[i]=1;//+1 else a[i]+=1; tp.a=toDigit(a); if(tp.a==e) return tp.t; if(vist[tp.a]==0) q.push(tp),vist[tp.a]=1; if(a[i]==1)a[i]=9; else a[i]--; if(a[i]==1) //-1 a[i]=9; else a[i]-=1; tp.a=toDigit(a); if(tp.a==e) return tp.t; if(vist[tp.a]==0) q.push(tp),vist[tp.a]=1; if(a[i]==9)a[i]=1;else a[i]++; if(i<3) //與前一個交換 { int tem=a[i]; a[i]=a[i+1]; a[i+1]=tem; tp.a=toDigit(a); if(tp.a==e) return tp.t; if(vist[tp.a]==0) q.push(tp),vist[tp.a]=1; tem=a[i]; a[i]=a[i+1]; a[i+1]=tem; } } } return -1; } int main() { int t; scanf("%d",&t); while(t--) { scanf("%d%d",&s,&e); int time=bfs(); printf("%d\n",time); } }