题解 | #玛雅人的密码#
玛雅人的密码
https://www.nowcoder.com/practice/761fc1e2f03742c2aa929c19ba96dbb0
当时卡住,主要是没有看到题目中说的只能交换相邻的两个字符,而不是说交换任意的字符顺序。
#include <iostream>
#include <set>
#include <queue>
using namespace std;
// 题目提醒的很明显,搜索!!!
int bfs(string s, int n) {
set<string> st;
queue<string> q;
int cnt = 0;
q.emplace(s);
while (!q.empty()) {
int size = q.size();
for (int k = 0; k < size; k++) {
string t = q.front();
q.pop();
if (t.find("2012") != string::npos) {
return cnt;
}
// 因为只能交换相邻的字母
for (int i = 1; i < n; i++) {
swap(t[i], t[i - 1]);
if (st.find(t) == st.end()) {
st.insert(t);
q.emplace(t);
}
swap(t[i], t[i - 1]);
}
}
cnt ++;
}
return -1;
}
int main() {
string s;
int n;
while (cin >> n >> s) {
cout << bfs(s, n) << endl;
}
}
