2 1234 2144 1111 9999
2 4
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
struct node
{
int a[4],step;
};
char str[2][5];
int f[4];
bool vis[10][10][10][10];
int BFS()
{
node now,next;
for(int i=0;i<4;i++)
{
now.a[i]=str[0][i]-'0';
f[i]=str[1][i]-'0';
}
memset(vis,false,sizeof(vis));
now.step=0;
queue<node>q;
q.push(now);
bool lock;
while(!q.empty())
{
now=q.front();
q.pop();
lock=true;
for(int i=0;i<4;i++)
{
if(now.a[i]!=f[i])
{
lock=false;
break;
}
}
if(lock)
return now.step;
for(int i=0;i<4;i++)//加一
{
next=now;
if(now.a[i]==9)
next.a[i]=1;
else
next.a[i]=now.a[i]+1;
if(!vis[next.a[0]][next.a[1]][next.a[2]][next.a[3]])
{
vis[next.a[0]][next.a[1]][next.a[2]][next.a[3]]=true;
next.step=now.step+1;
q.push(next);
}
}
for(int i=0;i<4;i++)//减一
{
next=now;
if(now.a[i]==1)
next.a[i]=9;
else
next.a[i]=now.a[i]-1;
if(!vis[next.a[0]][next.a[1]][next.a[2]][next.a[3]])
{
vis[next.a[0]][next.a[1]][next.a[2]][next.a[3]]=true;
next.step=now.step+1;
q.push(next);
}
}
for(int i=0;i<3;i++)//交换
{
next=now;
next.a[i]=now.a[i+1];
next.a[i+1]=now.a[i];
if(!vis[next.a[0]][next.a[1]][next.a[2]][next.a[3]])
{
vis[next.a[0]][next.a[1]][next.a[2]][next.a[3]]=true;
next.step=now.step+1;
q.push(next);
}
}
}
return -1;
}
int main()
{
int t;
cin>>t;
while(t--)
{
cin>>str[0]>>str[1];
cout<<BFS()<<endl;
}
return 0;
}
HDU 1195 Open the Lock (不一样的BFS)
原文:http://blog.csdn.net/hurmishine/article/details/51883394