#include<iostream>
#include<memory.h>
#include<stack>
#include<string>
#include<cmath>
#include<map>
#include<algorithm>
#include<sstream>
#include<set>
#include<queue>
//青蛙跳格子,我采用裸广搜的方法,几秒可以出答案,但是有时间限制就不行了
//将青蛙跳看作是,圆盘跳动,这样就只有一个变量在变化了
//将圆盘看成是0,初始序列用012345678表示,在广搜的时候用set判一下重
using namespace std;
struct node
{
string str;
int pos;
int step;
node(string str,int pos,int step):str(str),pos(pos),step(step){}
};
int N=9;
set<string> visited;
queue<node> q;
void insertq(node no,int i)
{
string s=no.str;
swap(s[no.pos],s[(no.pos+i+9)%9]);
if(visited.count(s)==0)
{
visited.insert(s);
node n(s,(no.pos+i+9)%9,no.step+1);
q.push(n);
}
}
int main()
{
node first("012345678",0,0);
q.push(first);
while(!q.empty())
{
node temp = q.front();
if(temp.str=="087654321")
{
cout<<temp.step;
break;
}
else
{
insertq(temp,1);
insertq(temp,-1);
insertq(temp,2);
insertq(temp,-2);
q.pop();
}
}
}
输出为20
转载于:https://www.cnblogs.com/WAoyu/p/8565388.html