hdu 1195 Open the Lock
Open the Lock
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 3210 Accepted Submission(s): 1412
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.
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.
Output
For each test case, print the minimal steps in one line.
Sample Input
2
1234
2144
1111
9999
Sample Output
2
4
Author
YE, Kai
Source
Zhejiang University Local Contest 2005
Recommend
Ignatius.L
//46MS 332K 1952 B C++ //bfs..想一口血喷在屏幕上,重点在11种转移的状态 #include<iostream> #include<queue> using namespace std; struct node{ int n; int cnt; }; int vis[10000]; int deal(int n,int i) { if(i>=0 && i<4){ if(i==0){ if(n%10==9) return n-8; else return n+1; }else if(i==1){ if(n/10%10==9) return n-80; else return n+10; }else if(i==2){ if(n/100%10==9) return n-800; else return n+100; }else{ if(n/1000==9) return n-8000; else return n+1000; } }else if(i>3 && i<8){ if(i==4){ if(n%10==1) return n+8; else return n-1; }else if(i==5){ if(n/10%10==1) return n+80; else return n-10; }else if(i==6){ if(n/100%10==1) return n+800; else return n-100; }else{ if(n/1000==1) return n+8000; else return n-1000; } }else{ if(i==8) return (n/1000*100)+(n%100)+1000*(n/100%10); else if(i==9) return (n%10)+100*(n/10%10)+n/1000*1000+10*(n/100%10); else return n/100*100+(n%10)*10+(n/10%10); } } int bfs(int n,int m) { memset(vis,0,sizeof(vis)); queue<node>Q; node t={n,0}; vis[n]=1; Q.push(t); while(!Q.empty()){ t=Q.front(); Q.pop(); if(t.n==m) return t.cnt; for(int i=0;i<11;i++){ node t0=t; int n0=deal(t0.n,i); if(!vis[n0]){ vis[n0]=1; t0.n=n0; t0.cnt++; Q.push(t0); //if(t0.n==1244) printf("**%d\n",t0.cnt); } } } } int main(void) { int n,m; int t; scanf("%d",&t); while(t--) { scanf("%d%d",&n,&m); printf("%d\n",bfs(n,m)); } return 0; }