如题,发了三个贴都没人答,跪求各位大佬大神了!!!
#include<iostream>
#include<string>
#include<queue>
#include<map>
using namespace std;
typedef long long ll;
map<ll,ll> cnt;
map<string,bool> buc;
ll head=0,tail=1;
string aim="123804765";
string str;
ll nextp(ll pos,ll id){
switch(id){
case 1:
if(pos-3>0)return pos-3;
break;
case 2:
if(pos+3<8)return pos+3;
break;
case 3:
if(pos%3!=0)return pos-1;
break;
case 4:
if(pos%3!=2)return pos+1;
//break;
}
return -1;
}
void bfs(string str){
if(str==aim){cout<<0;return;}
queue<string> q;
q.push(str);
bool flag=false;
while(!q.empty() and !flag){
string now=q.front();q.pop();
ll pos=now.find('0');
for(ll i=1;i<=4;i++){
ll ds=nextp(pos,i);
if(ds==-1)continue;
swap(now[pos],now[ds]);
if(!buc[now]){
if(now==aim){cout<<cnt[head]+1;flag=true;break;}
cnt[tail++]=cnt[head]+1;
q.push(now);
buc[now]=1;
}
swap(now[pos],now[ds]);
}
head+=1;
}
}
int main(){
cin>>str;
bfs(str);
return 0;
}```