题解 | #玛雅人的密码#

玛雅人的密码

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

解题思路:

BFS: 当前状态为当前字符串,其延伸出去的下一系列状态 就是 各种移位之后的字符串 如果之前没有被访问过,就放入队列中

判断当前字符串如果满足提议 就直接返回深度

这里深度的计算 我用了个很妙的地方 visited key为字符串,value为深度 判断有没有访问过 可以直接调用count来判断

然后每次入队前,给value赋值,深度加一!!!

这个地方如何判断无解了 因为该字符串移位的所有情况是有限的,所以当所有字符串都被访问过时,队列肯定存在为空的情况

在外面循环 返回-1 即可

#include <any>
#include <bits/stdc++.h>
#include <cstring>
#include <queue>
using namespace std;

int n;
string str;
map<string,int> visited; //判断结点是否被访问过 且用value来存储深度

bool isContain(string str){ //判断字符串中是否存在子串“2012”
    if(str.find("2012") == -1) return false;
    return true;
}


int BFS(string s){
    queue<string> q;
    q.push(s);
    visited[s] = 0;
    while(!q.empty()){
        string current = q.front();
        if(isContain(current)) return visited[current];
        //todo 判断结束
        q.pop();
        for(int i = 0; i < current.size() - 1; i++){
            string temp = current;
            swap(temp[i], temp[i+1]); //交换字符串
            if(visited.count(temp) == 0) { //说明之前未被访问过 则 入队
                   q.push(temp);
                   visited[temp] = visited[current] + 1; //深度加一
            }
        }
        
    }
    return -1; //说明此时无解

}

int main() {

    while (cin >> n) { // 注意 while 处理多个 case
        cin >> str;
        if(n <= 3) {
            cout << -1 << endl;
            continue;
        }
        cout << BFS(str) << endl;

    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务