//DFS P145习题 玛雅人的密码
//https://www.nowcoder.com/practice/761fc1e2f03742c2aa929c19ba96dbb0?tpId=60&tqId=29484&tPage=1&ru=/kaoyan/retest/1001&qru=/ta/tsing-kaoyan/question-ranking
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <cstring>
#include <queue>
#include <map>
using namespace std;
map<string, int> m; //相当于visit的作用
struct Node{
char s[14];//代表字符串
int num;//代表移动次数
};
void MoveString(queue<Node> &q,Node n,int N){//每移动一次字符串得到的字符串
char ch;
Node temp;
for(int i = 0;i < N;i++){ //自己:修改为i<N-1 N+1也对 自己感觉最好写N-1
strcpy(temp.s,n.s);
ch = temp.s[i]; //没有必要 直接swap
temp.s[i] = temp.s[i+1];
temp.s[i+1] = ch;
temp.num = n.num + 1;
m[temp.s] = 0; //这里的标记不对 否则会重复处理
q.push(temp); //存储在待处理的队列中
}
return ;
}
int main(){
char p[14];//待处理字符串
int N;
while(scanf("%d",&N) != EOF){ //整数N,代表字符串的长度 没有问题
scanf("%s",p);
queue<Node> q; //BFS
Node n;
int flag = 0; //标记是否已经查找成功
strcpy(n.s,p); n.num = 0; m[p] = 0; q.push(n);
while(!q.empty()&&flag == 0){
n = q.front();
if(m[n.s] == 1){//如果该密码已经寻找过了就直接删除
q.pop();
}else{
if(strstr(n.s,"2012") != NULL){//使用string库函数判断是否出现2012
printf("%d\n",n.num);
flag = 1;
}else{//在该字符串中并没有找到2012
MoveString(q,n,N);
m[n.s] = 1;//标记该密码已经修改过
q.pop();
}
}
}
if(flag == 0){//如果无论移动多少次都无法找到指定字符串
printf("-1\n");
}
}
return 0;
}