#include <stdio.h> struct node{ int a[4]; int step; }first,last; node num[10000]={0}; int d[10][10][10][10]={0}; int tail=0,head=0; int g[10]; int h=0; void en(node E) //先进栈 { num[tail++]=E; } node jm() { return num[head++]; //在出栈 } void fun() { first.step=0; node source={first.a[0],first.a[1],first.a[2],first.a[3],first.step}; d[first.a[0]][first.a[1]][first.a[2]][first.a[3]]=1; en(source); //先把数字存入数组中 node cur=first; node ns={}; while(head<tail) { cur=jm(); if(cur.a[0]==last.a[0]&&cur.a[1]==last.a[1]&&cur.a[2]==last.a[2]&&cur.a[3]==last.a[3]) { g[h++]=cur.step; break; } for(int i=0;i<4;i++) { ns=cur; ns.a[i]++; if(ns.a[i]==10) ns.a[i]=1; if(!d[ns.a[0]][ns.a[1]][ns.a[2]][ns.a[3]]) { d[ns.a[0]][ns.a[1]][ns.a[2]][ns.a[3]]=1; ns.step++; en(ns); } } for(int i=0;i<4;i++) { ns=cur; ns.a[i]--; if(ns.a[i]==0) ns.a[i]=9; if(!d[ns.a[0]][ns.a[1]][ns.a[2]][ns.a[3]]) { d[ns.a[0]][ns.a[1]][ns.a[2]][ns.a[3]]=1; ns.step++; en(ns); } } for(int i=0;i<4;i++) { ns=cur; int l; l=ns.a[i]; ns.a[i]=ns.a[i+1]; ns.a[i+1]=l; if(!d[ns.a[0]][ns.a[1]][ns.a[2]][ns.a[3]]) { d[ns.a[0]][ns.a[1]][ns.a[2]][ns.a[3]]=1; ns.step++; en(ns); } } } } void main() { char c1[10],c2[10]; int t; scanf("%d",&t); while(t--) { scanf("%s %s",c1,c2); for(int i=0;i<4;i++) { first.a[i]=c1[i]-'0'; last.a[i]=c2[i]-'0'; } fun(); } for(int m=0;m<h;m++) { printf("%d ",g[m]); } }
Problem 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. 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.
Now your task is to use minimal steps to open the lock.
Note: The leftmost digit is not the neighbor of the rightmost digit.
Input
The 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.
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.
Output
For each test case, print the minimal steps in one line.
Sample Input
2
1234
2144
1111
9999
Sample Output
2
4