Open the Lock
Description
Now the emergent task for are to open a password lock. The password is consisted of four digits. Each digit are numbered from 1 to 9.
Each time, you can add or minus 1 to any digit. When add 1 to ' 9 ', the digit would change to IS ' 1 ' and when minus 1 to ' 1 ', the digit would change to be ' 9 '. You can also exchange the digit with its neighbor. Each action would take one step.
Now your task was 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 is 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 a blank line after each test case.
Output
For each test case, print the minimal steps on one line.
Sample Input
Sample Output
#include <stdio.h> #include <queue> #include <iostream>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<node>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)//With previous interchange {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); }}
Hdu1195open the Lock (BFS)