玛雅人的密码(BFS)

本文通过深度优先搜索(DFS)方法解决了一道关于玛雅人密码的编程题,详细阐述了代码实现过程。

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

题目链接:

https://www.nowcoder.com/practice/761fc1e2f03742c2aa929c19ba96dbb0?tpId=40&tqId=21343&tPage=1&rp=1&ru=/ta/kaoyan&qru=/ta/kaoyan/question-ranking

代码如下:

#include <bits/stdc++.h>
using namespace std;
map<string,int> maps;  //存储对应字符串需要的移位次数
bool Satisfy(string str){ //判断是否满足解密条件
    if(str.find("2012")!=string::npos){ //判断str中是否有“2012”这个串
        return true;
    }else{
        return false;
    }
}
string exchange(string str,int i,int j){  //交换字符串str两个位置的元素
    string strTmp=str;
    char c=strTmp[i];
    strTmp[i]=strTmp[j];
    strTmp[j]=c;
    return strTmp;
}
int BFS(string str){
    queue<string> myQueue;
    myQueue.push(str);
    maps.clear();//每次输入案例需清空maps
    maps[str]=0;//原始字符串移位0次
    while(!myQueue.empty()){
        string strTmp=myQueue.front();
        myQueue.pop();
        if(Satisfy(strTmp)){
            return maps[strTmp];
        }
        for(int i=1;i<strTmp.size();i++){
              string newStr=exchange(strTmp,i-1,i);
              if(maps.find(newStr)==maps.end()){//newStr未出现过
                  maps[newStr]=maps[strTmp]+1;//移位次数加1
                  myQueue.push(newStr);//新字符串压入队列
              }
        }
    }
    return -1;//遍历完所有可能仍没有找到符合条件的字符串
}
int main(){
    int n;
    while(scanf("%d",&n)!=EOF){
        string str;
        cin>>str;
        printf("%d\n",BFS(str));
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值