127. 单词接龙

int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
    unordered_set<string> wordDict(wordList.begin(), wordList.end());
    if (wordDict.find(endWord) == wordDict.end()){
        return 0;
    }
    unordered_set<string> beginSet{beginWord};
    unordered_set<string> endSet{endWord};
    int step = 1;
    for (; !beginSet.empty();){
        unordered_set<string> tempSet;
        ++step;
        for (auto s : beginSet) {    //去除遍历过的变化
            wordDict.erase(s);
        }
        for (auto s : beginSet) {
            for (int i = 0; i < s.size(); ++i){
                string str = s;
                for (char c = 'a'; c <= 'z'; ++c){
                    str[i] = c;
                    if (wordDict.find(str) == wordDict.end()){   //不规范的基因变化,或者已经遍历过的变化
                        continue;
                    }
                    if (endSet.find(str) != endSet.end()){      //beginSet与endSet两边的bfs相遇
                        return step;
                    }
                    tempSet.insert(str);    //从beginSet出发的下一轮的基因变化
                }
            }
        }
        if (tempSet.size() < endSet.size()){  //每次都从中间结果少的那一端出发
            beginSet = tempSet;
        } else {
            beginSet = endSet;
            endSet = tempSet;
        }
    }
    return 0;
}

你可能感兴趣的:(LeetCode,c++,BFS)