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
思路
这道题更快的做法我觉得应该是双向广搜拓展内存消耗和时间上比单广更优。先贴一个单广的做法。注意状态转移,第一个数字和最后一个数字不是邻居。当添加1到‘9’时,数字将更改为‘1’,而当减去1到‘1’时,该数字将更改为‘9’。那么状态转移就只有11种状态了。4加法 + 4减法 + 3交换
#include <iostream>
#include <algorithm>
#include <queue>
#include <cstring>
using namespace std;
struct Node{
int x,step;
bool operator <(const Node& s)const{
return s.step < step;
}
};
priority_queue<Node>q;
int a[4];
bool visited[10001];
void new_set()
{
while(!q.empty()){
q.pop();
}
memset(visited,false,sizeof(visited));
}
void bfs(int x,int y)
{
Node p;
p.x = x;p.step = 0;
visited[x] = true;
q.push(p);
while(!q.empty()){
p = q.top();
q.pop();
if(p.x == y){
cout<<p.step<<endl;
break;
}
for(int i = 0;i <= 10;i++){
a[0] = p.x/1000;a[1] = p.x/100%10;a[2] = p.x/10%10;a[3] = p.x%10;
if(i <= 2){
int t = a[i];
a[i] = a[i+1];
a[i+1] = t;
}
else if(i <= 6){
a[(i+1)%4] += 1;
if(a[(i+1)%4] > 9){
a[(i+1)%4] = 1;
}
}
else if(i <= 10){
a[(i+1)%4] -= 1;
if(a[(i+1)%4] <= 0){
a[(i+1)%4] = 9;
}
}
Node ptr;
ptr.x = a[0]*1000+a[1]*100+a[2]*10+a[3];
if(visited[ptr.x] == false){
ptr.step = p.step + 1;
visited[ptr.x] = true;
q.push(ptr);
}
}
}
}
int main()
{
int n;
cin>>n;
while(n--){
int x,y;
cin>>x>>y;
new_set();
bfs(x,y);
}
return 0;
}
愿你走出半生,归来仍是少年~