leetcode刷题.127. 单词接龙.每日打卡

bfs的经典题目:代码:

class Solution {
public:

        int ladderLength(string beginWord, string endWord, vector<string>& wordList) {

                int minLength = INT_MAX;
                // 构造图的邻接举证表示
                unordered_map<string, vector<string>> stringMap;
                for(const auto &s : wordList) {
                    if(canConvert(beginWord, s))
                        stringMap[beginWord].push_back(s);
                }

                for(const auto &s1 : wordList) {
                    for(const auto &s2 : wordList) {
                        if(canConvert(s1, s2))
                            stringMap[s1].push_back(s2);
                    }
                }

                /* 广度优先搜索 */
                queue<int> q1;
                queue<string> q2;
                unordered_set<string> hashmap;
                q1.push(1);
                q2.push(beginWord);
                hashmap.insert(beginWord);

                while(q1.size()) {

                    int len = q1.front();
                    string word = q2.front();
                    q1.pop();
                    q2.pop();

                    if(word == endWord) {
                        if(minLength > len)
                            minLength = len;
                    }

                    const vector<string> &wordlist = stringMap[word];
                    for(const auto &w : wordlist) {
                        if(hashmap.end() == hashmap.find(w)) {
                            q1.push(len + 1);
                            q2.push(w);
                            hashmap.insert(w);
                        }
                    }                   
                }
                return minLength == INT_MAX ? 0 : minLength;
        }
private:
        /* 假定A和B不为空且长度相等 */
        bool canConvert(const string &A, const string &B) {
            int count = 0;
            for(int i = 0; i < A.length(); i++) {
                if(A[i] != B[i])
                    count++;
            }
            return (count <= 1);
        }

};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值