Open the Lock
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 7603 Accepted Submission(s): 3397
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
题目分析:
问从初始的密码到目的的密码的最少操作次数,每位上的数有三种操作,加一,减一,交换。没什么问题,就是将三种情况算一下,然后入队列,出队的时候判断一下情况就行了。已得到的密码记得标记一下。
代码:
#include<iostream>
#include<queue>
#include<string>
using namespace std;
struct Node {
string k;
int step;
Node(string kk = "", int s = 0) {
k = kk; step = s;
}
};
string key;
string target;
queue<Node> q;
int vis[100005];
string add(string t, int index) {
int a = t[index] - '0';
if(a!=8)
t[index] = (a + 1) % 9 + '0';
else t[index] = '9';
return t;
}
string Minus(string t, int index) {
int a = t[index] - '0';
if(a!=1)
t[index] = (a - 1) % 9+'0';
else t[index] = '9';
return t;
}
string exchange(string t, int index1, int index2) {
char temp = t[index1];
t[index1] = t[index2];
t[index2] = temp;
return t;
}
int BFS() {
Node temp;
while (!q.empty())q.pop();
q.push(Node(key,0));
while (!q.empty())
{
temp = q.front();
q.pop();
if (temp.k == target) { return temp.step; }
int st = temp.step+1;
for (int i = 0; i < 4; i++)
{
//加一操作
string p = add(temp.k, i);
if (!vis[(p[0] - '0') * 1000 + (p[1] - '0') * 100 + (p[2] - '0') * 10 + (p[3] - '0')]) {
vis[(p[0] - '0') * 1000 + (p[1] - '0') * 100 + (p[2] - '0') * 10 + (p[3] - '0')] = 1;
q.push(Node(p, st));
}
//减一操作
p = Minus(temp.k, i);
if (!vis[(p[0] - '0') * 1000 + (p[1] - '0') * 100 + (p[2] - '0') * 10 + (p[3] - '0')]) {
vis[(p[0] - '0') * 1000 + (p[1] - '0') * 100 + (p[2] - '0') * 10 + (p[3] - '0')] = 1;
q.push(Node(p, st));
}
//交换操作
if (i != 3) {
if (temp.k[i] != temp.k[i + 1]) {
p = exchange(temp.k, i, i + 1);
if (!vis[(p[0] - '0') * 1000 + (p[1] - '0') * 100 + (p[2] - '0') * 10 + (p[3] - '0')]) {
vis[(p[0] - '0') * 1000 + (p[1] - '0') * 100 + (p[2] - '0') * 10 + (p[3] - '0')] = 1;
q.push(Node(p, st));
}
}
}
}
}
}
int main() {
int T;
cin >> T;
while (T--)
{
memset(vis, 0, sizeof(vis));
cin >> key>>target;
cout << BFS() << endl;
}
return 0;
}