没有任何优化的无脑暴力bfs
#include<iostream> #include<queue> #include<string> using namespace std; struct mitery{ int index; string s; mitery(int i,string ss):index(i),s(ss){} }; void bfs(string s){ queue<mitery> q; q.push(mitery(0,s)); while(!q.empty()){ mitery t=q.front(); q.pop(); string ts=t.s; if(ts.find("2012")!=string::npos){ cout<<t.index<<endl;return ; } for(int i=0;i<ts.size()-1;i++){ swap(ts[i],ts[i+1]); q.push(mitery(t.index+1,ts)); swap(ts[i],ts[i+1]); } } cout<<-1<<endl; } int main(){ int n; string s; while(cin>>n>>s){ bfs(s); } return 0; }