[leetcode] word ladder

题目本质上就是图的最短路问题,用BFS的话写起来比较容易


class Solution {
public:
    int ladderLength(string start, string end, unordered_set<string> &dict) {
        if(start.length() != end.length()){
            return 0;
        }

        int N = start.length();
        queue<string> q1,q2;
        q1.push(start);
        if(dict.find(start) != dict.end()){
            dict.erase(start);
        }
        int result = 1;
        while(!q1.empty()){
            while(!q1.empty()){
                string cur = q1.front();
                if (oneStep(cur, end)) {
                    return result+1;
                }
                q1.pop();
                vector<string> nextWords = nexts(cur, dict);
                for(int i = 0; i < nextWords.size(); i++){
                    string next = nextWords[i];
                    dict.erase(next);
                    q2.push(next);
                }
            }
            swap(q1, q2);
            result++;
        }
        return 0;
        
    }
    
    vector<string> nexts(string word, unordered_set<string> &dict){
        vector<string> result;
        int N = word.length();
        for(int i = 0; i < N; i++){
            char ori = word[i];
            for(char c = 'a'; c <= 'z'; c++){
                word[i] = c;
                if(dict.find(word) != dict.end()){
                    result.push_back(word);
                }
            }
            word[i] = ori;
        }
        return result;
    }
    
    //两个string之间的距离是否为1
    bool oneStep(string s1, string s2){
        if(s1.length() != s2.length() || s1 == s2){
            return false;
        }

        int N = s1.length();
        int result = 0;
        for(int i = 0; i < N; i++){
            if(s1[i] != s2[i]){
                result++;
            }
            if(result >1){
                return false;
            }
        }
        return result == 1;
    }
};


你可能感兴趣的:(LeetCode)