玛雅人的密码

这篇文章揭秘了清华大学复试上机题中关于玛雅人密码的广度优先搜索算法实现,带你探索字符串移位谜题的解法过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目名称:玛雅人的密码
题目来源:清华大学复试上机题
题目链接: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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值