http://oj.ecustacm.cn/problem.php?id=1318
#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
#include<queue>
#include<map>
using namespace std;
string s1="012345678";//当前状态
string s2="087654321";//最终状态
int dx[4]={1,2};//顺时针跳
int dy[4]={-1,-2};//逆时针跳
struct node
{
int x;
int step;
string s;
}Node;
void bfs(int x)
{
Node.x=0;
Node.step=0;
Node.s=s1;
queue<node>q;
q.push(Node);
map<string,int>mp;
mp[s1]=1;
while(!q.empty())
{
node top=q.front();
q.pop();
for(int i=0;i<2;i++)
{
int tempx=(top.x+dx[i])%9;
string str=top.s;
swap(str[top.x],str[tempx]);
if(!mp[str])
{
node m;
m.x=tempx;
m.step=top.step+1;
m.s=str;
mp[str]=1;
if(str==s2)
{
cout<<m.step<<endl;
return ;
}
q.push(m);
}
}
for(int i=0;i<2;i++)
{
int tempx=top.x+dy[i];
if(tempx==-1) tempx=8;
if(tempx==-2) tempx=7;
string str=top.s;
swap(str[top.x],str[tempx]);
if(!mp[str])
{
node m;
m.x=tempx;
m.step=top.step+1;
m.s=str;
mp[str]=1;
if(str==s2)
{
cout<<m.step<<endl;
}
q.push(m);
}
}
}
}
int main(void)
{
bfs(0);
//cout<<20<<endl;
return 0;
}
简写:
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
#include<map>
#include<queue>
using namespace std;
string s="012345678";
string cmp="087654321";
int dx[4]={1,2,-1,-2};
struct node
{
int x,step;
string s;
}Node;
void bfs(int x)
{
Node.x=x,Node.step=0,Node.s=s;
queue<node>q; q.push(Node);
map<string,int>mp; mp[s]=1;
while(!q.empty())
{
node top=q.front();
q.pop();
for(int i=0;i<2;i++)
{
int tempx=(top.x+dx[i])%9;
string ss=top.s;
swap(ss[top.x],ss[tempx]);
if(!mp[ss])
{
node m;
m.x=tempx, m.step=top.step+1;
m.s=ss, mp[ss]=1;
if(ss==cmp)
{
cout<<m.step<<endl;
return;
}
q.push(m);
}
}
for(int i=0;i<2;i++)
{
int tempx=top.x+dx[i+2];
if(tempx==-1) tempx=8;
if(tempx==-2) tempx=7;
string ss=top.s;
swap(ss[top.x],ss[tempx]);
if(!mp[ss])
{
node m;
m.x=tempx, m.step=top.step+1;
m.s=ss, mp[ss]=1;
if(m.s==cmp)
{
cout<<m.step<<endl;
return;
}
q.push(m);
}
}
}
}
int main(void)
{
bfs(0);
return 0;
}