6.Word Ladder

https://leetcode.com/problems/word-ladder/

class Solution {
public:
    int ladderLength(string beginWord, string endWord, unordered_set& wordList) {
        if (beginWord == endWord) {
            return 1;
        }
        
        int count = 2;
        int ws = beginWord.length();
        queue q;
        q.push(beginWord);
        wordList.erase(beginWord);
        
        while (!q.empty()) {
            int n = q.size();
            for (int i = 0; i < n; i++) {
                string word = q.front();
                q.pop();
                for (int ci = 0; ci < ws; ci++) {
                    char och = word[ci];
                    for (char nch = 'a'; nch <= 'z'; nch++) {
                        word[ci] = nch;
                        if (word == endWord) {
                            return count;
                        }
                        if (wordList.find(word) != wordList.end()) {
                            q.push(word);
                            wordList.erase(word);
                        }
                    }
                    word[ci] = och;
                }
            }
            count++;
        }
        
        return 0;
    }
};

你可能感兴趣的:(6.Word Ladder)