c_cpp [bfs] [string]字梯。给定两个单词(开头和结尾)和一个字典,从星上找到最短变换序列的长度

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp [bfs] [string]字梯。给定两个单词(开头和结尾)和一个字典,从星上找到最短变换序列的长度相关的知识,希望对你有一定的参考价值。

/*
Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:

Only one letter can be changed at a time
Each intermediate word must exist in the dictionary
For example,

Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.

Note:
Return 0 if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
*/

#include <iostream>
#include <string>
#include <unordered_set>
#include <queue>
using namespace std;

int shortest(const string& s, const string& t, unordered_set<string>& dict) {
    if(s.size() != t.size()) return 0;
    if(s == t) return 0; // 
    unordered_set<string> used;
    int level1, level2;
    queue<string> q;
    q.push(s);
    used.insert(s);
    level1 = 1;
    level2 = 0;
    int jumps = 1;
    while(!q.empty()) {
        string st = q.front();
        q.pop();
        level1--;
        if(st == t) return jumps;
        for(int i=0; i<st.size(); i++) {
            string copy(st);
            for(int j=1; j<=26; j++) {
                copy[i] = 'a' + j - 1;
                if(st == copy) continue;
                if(dict.find(copy) == dict.end()) continue;
                if(used.find(copy) != used.end()) continue;
                q.push(copy);
                used.insert(copy);
                level2++;
            }
        }
        if(level1 == 0) {
            jumps++;
            level1 = level2;
            level2 = 0;
        }
    }
    return 0;
}

int main()
{
    unordered_set<string> dict = {"ab", "ac", "xc"};
    cout << shortest("ab", "xc", dict);
}

以上是关于c_cpp [bfs] [string]字梯。给定两个单词(开头和结尾)和一个字典,从星上找到最短变换序列的长度的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp 图表-BFS

c_cpp BFS

c_cpp 图表的BFS

c_cpp bfs.cpp

c_cpp BFS(宽度优先搜索算法)-C ++

c_cpp [tree] [dfs] [bfs]二叉树的最小深度