2017省赛A第2题
#include<bits/stdc++.h>
using namespace std;
struct node{
string str;//当前的状态
int pos;//当前0的位置
int step;//所走的步数
node(string str,int pos,int step):str(str),pos(pos),step(step){}
};
int N=9;
int nextstep[4]={1,-1,2,-2};
set<string> vis;
queue<node> q;
void bfs()
{
node start("012345678",0,0);
q.push(start);
while(!q.empty()){
node temp=q.front();
q.pop();
if(temp.str=="087654321"){
cout<<temp.step;
break;
}
for(int i=0;i<4;i++){
string s=temp.str;
swap(s[temp.pos],s[(temp.pos+nextstep[i]+9)%9]);//开始进行跳跃
if(vis.count(s)==0){//如果跳跃后的状态是新的状态(未出现),则将其状态保存
vis.insert(s);
node next_node(s,(temp.pos+nextstep[i]+9)%9,temp.step+1);
q.push(next_node);
}
}
}
}
int main()
{
bfs();
return 0;
}