题解 | #玛雅人的密码#

玛雅人的密码

https://www.nowcoder.com/practice/761fc1e2f03742c2aa929c19ba96dbb0

广度优先搜索,用了unordered_map标记字符串是否已经被访问过

#include <iostream>
#include <queue>
#include "queue"
#include "unordered_map"
using namespace std;
struct status {
    string code;
    int count;
    status(string s, int a) {
        code = s;
        count = a;
    }
};
int bfs(string code){
        queue<status> countQueue;
        unordered_map<string,bool> visitMap;
        countQueue.push(status(code, 0));
        visitMap[code]=true;
        while (!countQueue.empty()) {
            status current = countQueue.front();
            countQueue.pop();
            if (current.code.find("2012") != string::npos) {
                return current.count;
            }
            for(int i=0;i<=code.size()-2;i++){
                string temp=current.code;
                swap(temp[i],temp[i+1]);
                if(visitMap[temp]) continue;
                countQueue.push(status(temp,current.count+1));
                visitMap[temp]=true;
            }
        }
        return -1;
}
int main() {
    int n;
    string code;
    while (cin >> n >> code) { // 注意 while 处理多个 case
        cout << bfs(code)<< endl;
        
    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

哇哇的菜鸡oc:他这不叫校招offer,而是实习offer
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务