N的每一位都可以加一或减一或跟相邻的一位交换位置,每操作一次算一步
求N以上面操作方法之后变成M的最少步数
代码:
#include<iostream>
#include<stdio.h>
#include<queue>
#include<string>
#include<string.h>
using namespace std;
struct Node
{
string str;
int cou;
}node, temp;
string password;
int f[2] = { 1, -1 };
int dis[10][10][10][10] = { 0 };
queue<Node> nodes;
void bfs()
{
while (!nodes.empty())
{
node = nodes.front();
nodes.pop();
if (node.str == password)
{
cout << node.cou << endl;
while (!nodes.empty())
{
nodes.pop();
}
return ;
}
else
{
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 2; ++j)
{
temp.str = node.str;
int num = temp.str[i] - '0' + f[j];
if (num == 0)
{
num = 9;
}
if (num == 10)
{
num = 1;
}
temp.str[i] = (num + '0');
if (!dis[temp.str[0] - '0'][temp.str[1] - '0'][temp.str[2] - '0'][temp.str[3] - '0'])
{
dis[temp.str[0] - '0'][temp.str[1] - '0'][temp.str[2] - '0'][temp.str[3] - '0'] = 1;
temp.cou = node.cou + 1;
nodes.push(temp);
}
temp = node;
int k = i + f[j];
if (k > 0 && k < 4)
{
char c = temp.str[i];
temp.str[i] = temp.str[k];
temp.str[k] = c;
if (!dis[temp.str[0] - '0'][temp.str[1] - '0'][temp.str[2] - '0'][temp.str[3] - '0'])
{
dis[temp.str[0] - '0'][temp.str[1] - '0'][temp.str[2] - '0'][temp.str[3] - '0'] = 1;
temp.cou++;
nodes.push(temp);
}
}
}
}
}
}
}
int main()
{
int t;
while (~scanf("%d", &t))
{
while (t--)
{
memset(dis, 0, sizeof(dis));
cin >> node.str >> password;
dis[node.str[0] - '0'][node.str[1] - '0'][node.str[2] - '0'][node.str[3] - '0'] = 1;
node.cou = 0;
nodes.push(node);
bfs();
}
}
return 0;
}