P1032 字串变换题解

题目传送门

C++代码

#include<bits/stdc++.h>

using namespace std;
const int N = 10;

string ar[N]; //由啥
string br[N]; //变成啥

int n; //规则个数
string a, b; //原串,目标串

//结构体
struct node {
    string str;
    int step;
};
//队列
queue<node> q;

//桶,利用set去重,检查
set<string> st;

//广度优先搜索
void bfs() {
    //标识原串已经使用过
    st.insert(a);

    //入队列
    q.push({a, 0});

    //广度优先
    while (!q.empty()) {
        auto p = q.front();
        q.pop();
        //如果找到
        if (p.str == b) {
            printf("%d
", p.step);
            return;
        }
        //大于10步还没有找到
        if (p.step > 10) {
            printf("NO ANSWER!
");
            return;
        }
        //尝试每一种变换方式
        for (int i = 0; i < n; i++) {
            //变换位置
            for (int j = 0; j < p.str.size(); j++) {
                //发现子串ar[i]
                if (p.str.compare(j, ar[i].size(), ar[i]) == 0) {
                    //拷贝出来新的,因为p.str后面还在循环,不能破坏
                    string s = p.str;
                    //替换,replace:从哪个下标位置开始,一共多长,替换成啥
                    s.replace(j, ar[i].size(), br[i]);
                    //没有出现过
                    if (!st.count(s)) {
                        st.insert(s);
                        q.push({s, p.step + 1});
                    }
                }
            }
        }
    }
    //这句话很重要噢~
    printf("NO ANSWER!
");//十步以内也无法变成b
}

int main() {
    //读入原串,目标串
    cin >> a >> b;
    //读入规则,按 ctrl+d结束
    while (cin >> ar[n] >> br[n]) n++;
    //广度优先搜索
    bfs();
    return 0;
}
原文地址:https://www.cnblogs.com/littlehb/p/15070311.html