Leetcode 127. 单词接龙

Leetcode126的弱化版本

class Solution {
public:
    bool differ_one(string &s, string &t) {
        int n = 0;
        for (int i = 0; i < s.size(); ++i)
            if ((n += s[i] != t[i]) > 1) return false;
        return n == 1;
    }
    int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
        int b = -1, e = -1, x;
        for (int i = 0; i < wordList.size(); ++i) {
            if (wordList[i] == beginWord) b = i;
            if (wordList[i] == endWord) e = i;
        }
        if (b == -1) wordList.push_back(beginWord), b = wordList.size() - 1;
        if (b == -1 || e == -1) return 0;
        queue<int> que;
        vector<int> index(wordList.size(), 0);//index代表第几层
        que.push(b), index[b] = 1;//b是端点
        while (index[e] == 0 && !que.empty()) {
            x = que.front(), que.pop();
            for (int i = 0; i < wordList.size(); ++i)
                if (index[i] == 0 && differ_one(wordList[x], wordList[i]))
                    index[i] = index[x] + 1, que.push(i);
        }
        return index[e];
    }
};

你可能感兴趣的:(Leetcode 127. 单词接龙)