rt,dalao 来帮忙看看。
#include <bits/stdc++.h>
using namespace std;
struct node{
string s;
int step;
node(string _s,int _step):s(_s),step(_step){}
};
map<string,bool> mp;
void bfs(string s){
queue<node> q;
mp[s] = 1;
q.push(node(s,0));
while(!q.empty()){
//找0
int pos;
for(int i = 0;i < 9;i++){
if(q.front().s[i] == '0'){
pos = i;
break;
}
}
for(int i = -3;i <= 3;i+=2){
if(pos+i < 0 || pos+i >= 9) continue;
int k = pos+i;
string ns = q.front().s;
swap(ns[pos],ns[k]);
if(!mp[ns]){
q.push(node(ns,q.front().step+1));
mp[ns] = 1;
if(ns == "123804765"){
cout<<q.back().step;
return;
}
}
}
q.pop();
}
}
int main(){
string s;
cin>>s;
bfs(s);
return 0;
}
剩下的都wa了