LeetCode -- 127. 单词接龙

 

方法一:双向广搜

class Solution {
public:
    int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
        set<string> se;
        for(auto it : wordList) {
            se.insert(it);
        }

        if(!se.count(endWord)) return 0;

        auto update = [&](queue<string> &q, unordered_map<string, int> &cur, unordered_map<string, int> &other) -> int {
            int m = q.size();
            while(m -- ) {
                string t = q.front();
                q.pop();
                int n = t.size();
                for(int i = 0; i < n; i ++ ) {
                    for(int j = 0; j < 26; j ++ ) {
                        string sub = t;
                        sub[i] = 'a' + j;
                        if(se.count(sub)) {
                            if(cur.count(sub)) continue;
                            if(other.count(sub)) {
                                return cur[t] + other[sub] + 1;
                            } else {
                                q.push(sub);
                                cur[sub] = cur[t] + 1;
                            }
                        }
                    }
                }
            }
            return -1;
        };

        auto bfs = [&]() -> int {
            queue<string> q1, q2;
            unordered_map<string, int> m1, m2;
            q1.push(beginWord);
            m1[beginWord] = 0;
            q2.push(endWord);
            m2[endWord] = 0;

            while(q1.size() && q2.size()) {
                int t = -1;
                if(q1.size() <= q2.size()) {  //注意这里等于号不能少,确保第一次若两个相等从起点开始搜索
                    t = update(q1, m1, m2);
                } else {
                    t = update(q2, m2, m1);
                }
                if(t != -1) return t;
            }
            return -1;
        };

        int res = bfs();
        return res == -1 ? 0: res + 1;
    }
};

 

posted @ 2023-08-09 09:07  深渊之巅  阅读(6)  评论(0编辑  收藏  举报