题目链接如下
http://acm.hdu.edu.cn/showproblem.php?pid=1195
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.
/*
考虑到此题密码变换规则相当复杂,但是数据并不是很大,密码只有4位,结果只要求输出最短的步数,可以考虑穷举法
假设结果是X种变换,我们第一步到第X步考虑每一种变换,每一种变换只有11种可能,变换后的密码又有11种可能,
如此重复,直到正确密码出现,然后直接输出变换的次数。
这里我们用 vis[10000] 这个数组表示每一种密码,
step[10000]数组保存变换到每一种密码所需要的最小步数
a[5],b[5]数组保存每个密码数字的值
q队列更新每次的密码值,且来控制循环
其实也就是bfs只是写法不同而已
*/
#include <iostream>
#include <queue>
using namespace std;
int n,m;
int step[10000];
bool vis[10000];
int main()
{
int N;
cin>>N;
while(N--)
{
cin>>n>>m;
if(n==m) cout<<"0"<<endl;
int i,flag,temp;
int a[5],b[5];
queue<int> q;
q.push(n);
memset(step,0,sizeof(step));
memset(vis,true,sizeof(vis));
while(!q.empty())
{
temp=q.front();
q.pop();
b[4]=a[4]=temp%10;
b[3]=a[3]=temp/10%10;
b[2]=a[2]=temp/100%10;
b[1]=a[1]=temp/1000;
for (i=0;i<11;i++)
{
switch (i)
{
case 0:
{
b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];
if (a[1]==9) b[1]=1;
else b[1]+=1;
}
break;
case 1:
{
b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];
if (a[2]==9) b[2]=1;
else b[2]+=1;
}
break;
case 2:
{
b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];
if (a[3]==9) b[3]=1;
else b[3]+=1;
}
break;
case 3:
{
b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];
if (a[4]==9) b[4]=1;
else b[4]+=1;
}
break;
case 4:
{
b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];
if (a[1]==1) b[1]=9;
else b[1]-=1;
}
break;
case 5:
{
b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];
if (a[2]==1) b[2]=9;
else b[2]-=1;
}
break;
case 6:
{
b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];
if (a[3]==1) b[3]=9;
else b[3]-=1;
}
break;
case 7:
{
b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];
if (a[4]==1) b[4]=9;
else b[4]-=1;
}
break;
case 8:
{
b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];
flag=b[1];
b[1]=a[2];
b[2]=flag;
}
break;
case 9:
{
b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];
flag=b[2];
b[2]=a[3]; b[3]=flag;
}
break;
case 10:
{
b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];
flag=b[3];
b[3]=a[4]; b[4]=flag;
}
break;
}
n=b[1]*1000+b[2]*100+b[3]*10+b[4];
if (vis[n])
{
vis[n]=false;
step[n]=step[temp]+1;
q.push(n);
if (n==m) { cout<<step[n]<<endl; break;}
}
}
}
}
}
密码锁解锁算法
本文介绍了一个基于穷举法的密码锁解锁算法。该算法通过遍历所有可能的密码变换步骤来寻找从初始状态到达目标状态所需的最少步数。适用于四数字密码锁。
779

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



