488. 祖玛游戏

文章目录

题意

题目链接

思路

dfs

代码

C++ 复制代码
class Solution {
public:
    string exchange(string tmp) {
        bool next = false;
        do{
            next = false;
            for (int l = 0, r = 0; l < tmp.size() && r < tmp.size(); l++) {
                r = l + 1;
                while (r < tmp.size() && tmp[l] == tmp[r] )
                    r++;
                if (r - l >= 3) {
                    tmp.erase(l, r - l);
                    next = true;
                    break;
                }
            }
        } while (next);
        return tmp;
    }
    int findMinStep(string board, string hand) {
        queue<pair<string, string>> Q;
        sort(hand.begin(), hand.end());
        Q.push(make_pair(board, hand));
        unordered_set<string> s;
        s.insert(board + "|" + hand);
        int step = 1;
        while (!Q.empty()) {
            int n = Q.size();
            for (int i = 0; i < n; i++) {
                const auto &index = Q.front();
                const string b = index.first;
                const string h = index.second;
                Q.pop();

                for (int j = 0; j < h.size(); j++) {
                    if (j > 0 && h[j] == h[j - 1])
                        continue;
                    for (int k = 0; k <= b.size(); k++) {
                        if (k > 0 && h[j] == b[k] && b[k] == b[k - 1])
                            continue;
                        if (!(k < b.size() && h[j] == b[k] || (k >= 1 && b[k - 1] == b[k])))
                            continue;
                        string c(1, h[j]);
                        string b_tmp = b.substr(0, k) + c + b.substr(k);
                        string b_next = exchange(b_tmp);
                        if (b_next == "")
                            return step;
                        string h_next = h.substr(0, j) + h.substr(j + 1);
                        string key = b_next + "|" + h_next;
                        if (s.find(key) == s.end()) {
                            Q.push(make_pair(b_next, h_next));
                            s.insert(key);
                        }
                    }
                }
            }
            step++;
        }
        return - 1;
    }
};
相关推荐
什巳1 小时前
JAVA练习306- 翻转二叉树
java·数据结构·算法·leetcode
smj2302_796826521 小时前
解决leetcode第3989题网格中保持一致的最大列数
python·算法·leetcode
巧克力男孩dd2 小时前
Python超典型练习题(第一次作业)
开发语言·python·算法
爱刷碗的苏泓舒3 小时前
平方根信息滤波:矩阵推导及 GNSS 参数估计应用
线性代数·算法·矩阵·gnss·参数估计·测量平差·平方根信息滤波
想做小南娘,发现自己是女生喵3 小时前
第 2 章 顺序表和 vector
java·数据结构·算法
艾醒4 小时前
2026年第29周(7.13-7.19)AI全复盘:技术突破、行业趣闻翻车、算力服务器商业动态
人工智能·算法
雪碧聊技术5 小时前
动态规划算法—01背包问题
算法·动态规划
bu_shuo5 小时前
c与cpp中的argc和argv
c语言·c++·算法
普贤莲花5 小时前
【2026年第29周---写于20260718】---整理,断舍离
程序人生·算法·生活
Reart5 小时前
Leetcode 674.最长连续递增序列 (719)
后端·算法