玛雅人的密码(BFS)

雨燕双飞 提交于 2020-02-09 15:13:52

题目链接:

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;
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!