Open the Lock
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 3847 Accepted Submission(s): 1661
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 | We have carefully selected several similar problems for you: 1072 1242 1240 1044 1254
题意:将第一行的4个数字变成第二行的数字
思路:利用广搜穷举所有情况。注意每一位可+1可-1,相邻两位可以交换位置,用一个visit[][][][]四维数组记录可能出现的数字串出现过没有。例如,"2143"出现过了,则 isv[2][1][4][3]=1。
#include <iostream> #include <cstdio> #include <cstring> #include <queue> using namespace std; int a[5],b[5]; int visit[10][10][10][10]; struct nodes { int num[5]; int m; }; nodes node1,node2; int bfs() { queue<nodes> q; while(!q.empty()) q.pop(); node1.num[0]=a[0]; node1.num[1]=a[1]; node1.num[2]=a[2]; node1.num[3]=a[3]; node1.m=0; visit[a[0]][a[1]][a[2]][a[3]]=1; q.push(node1); while(!q.empty()) { node1=q.front(); q.pop(); if(node1.num[0]==b[0]&&node1.num[1]==b[1]&&node1.num[2]==b[2]&&node1.num[3]==b[3]) return node1.m; for(int i=0;i<4;i++) { node2=node1; if(node1.num[i]==9) node2.num[i]=1; else node2.num[i]=node1.num[i]+1; if(!visit[node2.num[0]][node2.num[1]][node2.num[2]][node2.num[3]]) { node2.m=node1.m+1; visit[node2.num[0]][node2.num[1]][node2.num[2]][node2.num[3]]=1; q.push(node2); } node2=node1; if(node1.num[i]==1) node2.num[i]=9; else node2.num[i]=node1.num[i]-1; if(!visit[node2.num[0]][node2.num[1]][node2.num[2]][node2.num[3]]) { node2.m=node1.m+1; visit[node2.num[0]][node2.num[1]][node2.num[2]][node2.num[3]]=1; q.push(node2); } } for(int i=0;i<3;i++) { node2=node1; node2.num[i]=node1.num[i+1]; node2.num[i+1]=node1.num[i]; if(!visit[node2.num[0]][node2.num[1]][node2.num[2]][node2.num[3]]) { node2.m=node1.m+1; visit[node2.num[0]][node2.num[1]][node2.num[2]][node2.num[3]]=1; q.push(node2); } } } return 0; } int main() { int t,t1,t2; scanf("%d",&t); while(t--) { memset(visit,0,sizeof(visit)); scanf("%d%d",&t1,&t2); int i=0,j=0; while(t1>0) { a[i++]=t1%10; t1=t1/10; } while(t2>0) { b[j++]=t2%10; t2=t2/10; } printf("%d ",bfs()); } }