30 Day Challenge Day 17 | Leetcode 127. Word Ladder

题解

Medium

方法:BFS

class Solution {
public:
    int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
        int steps = 0;
        
        unordered_set<string> dict(wordList.begin(), wordList.end());
        
        if(!dict.count(endWord)) return 0;
        
        queue<string> q;
        q.push(beginWord);
        
        while(!q.empty()) {
            steps++;
            int sz = q.size();
            for(int i = 0; i < sz; i++) {
                string t = q.front();
                q.pop();
                
                for(int k = 0; k < t.size(); k++) {
                    char ch = t[k];
                    for(int c = 'a'; c <= 'z'; c++) {
                        t[k] = c;
                        if(t == endWord) return steps+1;
                        if(dict.count(t)) {
                            dict.erase(t);
                            q.push(t);
                        }
                        t[k] = ch;
                    }
                }
            }
        }
        
        return 0;
    }
};

方法:Bi-directional BFS

更进一步,可以用双向广度优先搜索。也就是用两个队列,分别从两端相互靠拢。

这里用 unordered_set 代替 queue 是考虑到后面用查找比较方便。

两条队列,每次处理较短的那条,也是一种节省时间的办法。

class Solution {
public:
    int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
        int steps = 0;
        
        unordered_set<string> dict(wordList.begin(), wordList.end());
        
        if(!dict.count(endWord)) return 0;
        
        unordered_set<string> q1, q2;
        q1.insert(beginWord);
        q2.insert(endWord);
        
        while(!q1.empty() && !q2.empty()) {
            steps++;
            
            if(q1.size() > q2.size()) {
                swap(q1, q2);
            }
            
            unordered_set<string> q;
            
            for(auto next : q1) {
                for(int k = 0; k < next.size(); k++) {
                    char ch = next[k];
                    for(int c = 'a'; c <= 'z'; c++) {
                        next[k] = c;
                        if(q2.count(next)) return steps+1;
                        if(dict.count(next)) {
                            dict.erase(next);
                            q.insert(next);
                        }
                        next[k] = ch;
                    }
                }
            }
            
            swap(q1, q);
        }
        
        return 0;
    }
};
原文地址:https://www.cnblogs.com/casperwin/p/13760334.html