您的位置:首页 > 运维架构

hdu 1195 Open the Lock(基础bfs)

2015-08-12 11:04 351 查看
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,减1,相邻交换,其中9+1=1,1-1=9,最左边不与最右边相邻。

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;
bool vis[10][10][10][10];
char str1[5],str2[5];
int des[5];
struct node
{
int num[5];
int step;
node()
{
step=0;
}
};
node start;

bool check(node &a)
{
if(!vis[a.num[0]][a.num[1]][a.num[2]][a.num[3]])
{
vis[a.num[0]][a.num[1]][a.num[2]][a.num[3]]=true;
return true;
}
return false;
}
bool ok(node &temp)
{
if(temp.num[0]==des[0] && temp.num[1]==des[1]&& temp.num[2]==des[2] && temp.num[3]==des[3])
return true;
return false;
}
int bfs()
{
queue<node>q;
memset(vis, false, sizeof(vis));
start.step=0;
q.push(start);
node temp;
while (!q.empty())
{
start=q.front();
q.pop();

for (int i=0; i<4; i++) //+1
{
temp=start;
temp.step++;
if(temp.num[i]!=9)
temp.num[i]++;
else
temp.num[i]=1;
if(check(temp))
{

if(ok(temp))
return temp.step;
q.push(temp);
}
}
for (int i=0; i<4; i++) //-1
{
temp=start;
temp.step++;
if(temp.num[i]!=1)
temp.num[i]--;
else
temp.num[i]=9;
if(check(temp))
{
if(ok(temp))
return temp.step;
q.push(temp);
}
}

for (int i=0; i<3; i++) //交换
{
temp=start;
temp.step++;
swap(temp.num[i], temp.num[i+1]);
if(check(temp))
{
if(ok(temp))
return temp.step;
q.push(temp);
}
}
}
return -1;
}

int main()
{
int t;
scanf("%d",&t);
getchar();
while (t--)
{
scanf("%s",str1);
getchar();
scanf("%s",str2);
getchar();
for(int i=0;i<4;i++)
{
start.num[i]=str1[i]-48;
des[i]=str2[i]-48;
}
printf("%d\n",bfs());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: