题目名称:玛雅人的密码
题目来源:清华大学复试上机题
题目链接:http://t.cn/Ai0lUhJj
#include <iostream>
#include <map>
#include <cstdio>
#include <algorithm>
#include <queue>
using namespace std;
int BFS(string str) {
map<string, int> myMap; //用于存储每一个字符串的移位次数
queue<string> sequence; //广度优先遍历队列
sequence.push(str);
myMap[str] = 0; //初始移位次数
int answer = -1;
while (!sequence.empty()) { //BFS
string current = sequence.front();
sequence.pop();
if (current.find("2012") != -1) { //查找成功则返回元素位置,不成功返回npos(-1)
answer = myMap[current];
break;
}
for (int i = 0; i < current.size() - 1; i++) {
string newStr = current;
swap(newStr[i], newStr[i + 1]);
if (myMap.count(newStr) == 0) { //count函数判断是否存在被查找元素,若使用find,查找成功返回元素位置,不成功返回map.end()
sequence.push(newStr);
myMap[newStr] = myMap[current] + 1;
}
}
}
return answer;
}
int main() {
int n;
while (cin >> n) {
string str;
cin >> str;
cout << BFS(str) << endl;
}
return 0;
}