题解 | #玛雅人的密码#借鉴了评论的
玛雅人的密码
https://www.nowcoder.com/practice/761fc1e2f03742c2aa929c19ba96dbb0
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <stack>
#include <map>
#include <queue>
using namespace std;
struct str {
int count; //记录移动的次数
string s;
};
bool check(string s) {
if (s.find("2012") != string::npos) {
return true;
} else {
return false;
}
}
queue<str> que;
int _count = -1;
void bfs(str s, int len) {
que.push(s);
//bfs主体
while (!que.empty()) { //队列非空时
str temp = que.front(); //取出队首
que.pop();
if (check(temp.s)) {
_count = temp.count;
return;
}
//移动字符,然后入队
for (int i = 0; i < len - 1; i++) {
swap(temp.s[i], temp.s[i + 1]); //交换相邻的两个字符
que.push({temp.count + 1, temp.s}); //把交换以后的放入队列中
swap(temp.s[i], temp.s[i + 1]); //交换以后还原
}
}
}
int main() {
int n;
str _str;
while (scanf("%d", &n) != EOF) {
cin >> _str.s;
if (n < 4) {
printf("-1\n");
continue;
}
int index;
if (index = _str.s.find('1') == string::npos) {
printf("-1\n");
continue;
}
if (index = _str.s.find('2') == string::npos) {
printf("-1\n");
continue;
}
if (index = _str.s.find('0') == string::npos) {
printf("-1\n");
continue;
}
int count2 = 0; //2的数量
for (int i = 0; i < _str.s.size(); i++) {
if (_str.s[i] == '2') {
count2++;
}
}
if (count2 < 2) {
printf("-1\n");
continue;
}
//此时_str.s符合要求
_str.count = 0;
bfs(_str, n);
printf("%d\n", _count);
}
}
主要是这个结构体的构造想不到,还有bfs的时候要怎么处理想不出来啊

