[Story of BFS and DFS] LC127---Word Solitaire (very classic BFS question, I am Gan)

The topic is as follows, so long

Insert picture description here

Thinking analysis

It must be the shortest conversion sequence if you find it in the wide search

Here I want to say that Guang search uses queues, and deep search uses stacks.

The wide search here is beginword. All 26 letters in each position are changed to search at one time. When the letter is found, the path is +1, and then enter the team, and continue searching after the search is completed at this level. Of course, if it is equal to endword, it will be output directly.

class Solution {
    
    
public:
    int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
    
    
        unordered_set<string> wordSet(wordList.begin(), wordList.end());
        if(!wordSet.count(endWord)) return 0;
        //用pathCount记录路径,转换到某一个字符串所需长度
        unordered_map<string, int> pathCount{
    
    {
    
    {
    
    beginWord, 1}}};
        queue<string> q{
    
    {
    
    beginWord}};
        while(!q.empty()){
    
    
            string word = q.front();
            q.pop();
            for(int i = 0; i < word.size(); i++){
    
    
                string newWord = word;
                for(char c = 'a'; c <= 'z'; c++){
    
    
                    newWord[i] = c;
                    if(wordSet.count(newWord) && newWord == endWord) return pathCount[word] + 1;
                    if(wordSet.count(newWord) && !pathCount.count(newWord)){
    
    
                        pathCount[newWord] = pathCount[word] + 1;
                        q.push(newWord);
                    }
                }
            }
        }
        return 0;
    }
};

Guess you like

Origin blog.csdn.net/qq_42136832/article/details/114395622
Recommended