http://acm.hdu.edu.cn/showproblem.php?pid=1195
bfs 加1 减 1 交换 ,三个方式
#include<stdio.h>
#include<iostream>
#include<math.h>
#include<stdlib.h>
#include<ctype.h>
#include<algorithm>
#include<vector>
#include<string.h>
#include<queue>
#include<stack>
#include<set>
#include<map>
#include<sstream>
#include<time.h>
#include<utility>
#include<malloc.h>
#include<stdexcept>
#include<iomanip>
#include<iterator>
using namespace std;
int t ;
char a[5],b[5];
struct node
{
int num[5];
int step;
};
node s1,s2;
int vis[10][10][10][10];
void bfs ()
{
memset (vis,0,sizeof(vis));
queue<node> q ;
node qq ,qqq;
s1.step = 0;
vis[s1.num[0]][s1.num[1]][s1.num[2]][s1.num[3]] = 1;
q.push(s1);
while (!q.empty())
{
int ok = 1;
qq = q.front();
q.pop();
for(int i=0;i<4;i++)
{
if (qq.num[i] != s2.num[i])
{
ok = 0;
break;
}
}
if (ok)
{
printf("%d\n",qq.step);
return ;
}
for(int i=0;i<4;i++)//减1
{
qqq = qq;
if (qq.num[i] == 1)
qqq.num[i] = 9;
else
qqq.num[i] = qq.num[i] - 1;
qqq.step = qq.step + 1;
if(!vis[qqq.num[0]][qqq.num[1]][qqq.num[2]][qqq.num[3]])
{
vis[qqq.num[0]][qqq.num[1]][qqq.num[2]][qqq.num[3]] = 1 ;
q.push(qqq);
}
}
for(int i=0;i<4;i++)//+1
{
qqq = qq;
if (qq.num[i] == 9)
qqq.num[i] = 1;
else
qqq.num[i] = qq.num[i] + 1;
qqq.step = qq.step + 1;
if(!vis[qqq.num[0]][qqq.num[1]][qqq.num[2]][qqq.num[3]])
{
vis[qqq.num[0]][qqq.num[1]][qqq.num[2]][qqq.num[3]] = 1 ;
q.push(qqq);
}
}
for(int i=0;i<3;i++)//替换
{
qqq = qq;
qqq.num[i] = qq.num[i+1];
qqq.num[i+1] = qq.num[i];
qqq.step = qq.step + 1;
if(!vis[qqq.num[0]][qqq.num[1]][qqq.num[2]][qqq.num[3]])
{
vis[qqq.num[0]][qqq.num[1]][qqq.num[2]][qqq.num[3]] = 1 ;
q.push(qqq);
}
}
}
return ;
}
int main()
{
scanf("%d",&t);
while (t--)
{
scanf("%s %s",a,b);
for(int i=0;i<4;i++)
{
s1.num[i] = a[i] - '0';
s2.num[i] = b[i] - '0';
}
bfs ();
}
return 0;
}