Open the Lock
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.
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.
2 1234 2144 1111 9999
2 4
#include<iostream>
#include<cstring>
using namespace std;
typedef struct digit {
int num[4];
int step;
} Q;
Q queue[10000];
int initial[4];
int password[4];
int visit[10][10][10][10];
int pre[10000];
int bfs(void) {
memset(visit, 0, sizeof (visit));
memset(queue, 0, sizeof (queue));
int qhead = 0;
int qtail = 0;
Q tmp;
for (int i = 0; i < 4; i++)
queue[qtail].num[i] = initial[i];
queue[qtail].step = 0;
visit[queue[qtail].num[3]][queue[qtail].num[2]][queue[qtail].num[1]][queue[qtail].num[0]] = 1;
qtail++;
while (qhead < qtail) {
for (int i = 0; i < 4; i++) {
tmp = queue[qhead];
tmp.step++;
tmp.num[i]++;
if (tmp.num[i] == 10)
tmp.num[i] = 1;
if (!visit[tmp.num[3]][tmp.num[2]][tmp.num[1]][tmp.num[0]]) {
int flag = 1;
for (int j = 0; j < 4; j++)
if (tmp.num[j] != password[j])
flag = 0;
if (flag)
return tmp.step;
visit[tmp.num[3]][tmp.num[2]][tmp.num[1]][tmp.num[0]] = 1;
queue[qtail++] = tmp;
}
tmp = queue[qhead];
tmp.step++;
tmp.num[i]--;
if (tmp.num[i] == 0)
tmp.num[i] = 9;
if (!visit[tmp.num[3]][tmp.num[2]][tmp.num[1]][tmp.num[0]]) {
int flag = 1;
for (int j = 0; j < 4; j++)
if (tmp.num[j] != password[j])
flag = 0;
if (flag)
return tmp.step;
visit[tmp.num[3]][tmp.num[2]][tmp.num[1]][tmp.num[0]] = 1;
queue[qtail++] = tmp;
}
if (i != 3) {
tmp = queue[qhead];
tmp.step++;
int t = tmp.num[i];
tmp.num[i] = tmp.num[i + 1];
tmp.num[i + 1] = t;
if (!visit[tmp.num[3]][tmp.num[2]][tmp.num[1]][tmp.num[0]]) {
int flag = 1;
for (int j = 0; j < 4; j++)
if (tmp.num[j] != password[j])
flag = 0;
if (flag)
return tmp.step;
visit[tmp.num[3]][tmp.num[2]][tmp.num[1]][tmp.num[0]] = 1;
queue[qtail++] = tmp;
}
}
}
qhead++;
}
}
int main(void) {
int t;
cin >> t;
while (t--) {
int tmp, tmp2;
cin >> tmp;
cin >> tmp2;
if (tmp == tmp2)
cout << '0' << endl;
else {
initial[0] = tmp % 10;
initial[1] = tmp / 10 % 10;
initial[2] = tmp / 100 % 10;
initial[3] = tmp / 1000 % 10;
password[0] = tmp2 % 10;
password[1] = tmp2 / 10 % 10;
password[2] = tmp2 / 100 % 10;
password[3] = tmp2 / 1000 % 10;
cout << bfs() << endl;
}
}
}
703




被折叠的 条评论
为什么被折叠?



