Leetcode 127 **

class Solution {
public:
    int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
        unordered_set<string> wordset(wordList.begin(),wordList.end());
        wordset.erase(beginWord);
        int res = 0;
        queue<string> que{{beginWord}};
        while(!que.empty()){
            int len = que.size();
            for(int i=0;i < len;i++){//坑:int i=0;i < que.size();i++  que.size()会不停改变
                string word = que.front(); que.pop();
                if(word == endWord) return res+1;
                for(int i=0;i < word.size();i++){
                    string newword = word;
                    for(char ch = 'a';ch <= 'z';ch++){
                        newword[i] = ch;
                        if(wordset.count(newword)){
                            que.push(newword);
                            wordset.erase(newword);
                        }
                    }
                }
            }
            res++;
        }
        return 0;  //没找到
    } 
};

好题!第一次见这题还是在一年前刚学算法的时候,今日硬着头皮分析了下去,前几天写的DFS T了,我都写了DFS居然没有想到这其实是一个求图的最短跳数的题:

单词之间能够变化可以抽象为两点之间有一条有向路径,BFS找到第一个点有向路径连接的所有点加入队列,然后对队列中的点再找图中剩下直连的点,最先到达终点的距离就是层数,直接返回。

还有要把层次遍历和BFS联系起来!都是用的队列,对每“批次”的队列遍历循环,两者本质是一样的。

最后注意 que.size()的坑,之前遇到过,还好看出来了。

猜你喜欢

转载自www.cnblogs.com/cunyusup/p/10569208.html
今日推荐