#include<iostream>
#include<queue>
#include<set>
using namespace std;
int n;
string s;
int ans;
set<string> S;
struct node{
string state;
int cnt;
node(string a ,int b){
state=a;
cnt=b;
}
};
queue<node> Q;
bool check(string x){
if(x.find("2012")==string::npos)
return false;
return true;
}
void bfs(){
while(!Q.empty()){
node t=Q.front();
Q.pop();
if(check(t.state)) {
cout<<t.cnt<<endl;
return ;
}
//继续交换
for(int j=0;j<t.state.size()-1;++j){
string s1=t.state;
swap(s1[j],s1[j+1]);
if(check(s1)) {
cout<<t.cnt+1<<endl;
return ;
}
if(S.find(s1)==S.end()){//如果这个序列之前没有出现过,进队
S.insert(s1);
Q.push(node(s1,t.cnt+1));
}
swap(s1[j],s1[j+1]);//换回来
}
}
cout<<-1<<endl;
return ;
}
int main()
{
cin>>n;
cin>>s;
Q.push(node(s,0));
S.insert(s);
bfs();
return 0;
}
蓝桥杯 算法提高 题目 2 密码锁(bfs)
最新推荐文章于 2024-03-26 11:16:17 发布