Leetcode127.单词接龙

思路:

    因为求的是最短路径,所以理所当然使用bfs,从 beginWord 开始,每次列举这个单词能变换的所有情况,如果在 wordList 中,就放入队列里继续进行 bfs,每次维护一个 path 用来记录变换成这个单词变换的次数。难度还是比较适中的

class Solution {
public:
    int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
        unordered_set<string> word(wordList.begin(),wordList.end());
        if(word.count(endWord)==0){
            return 0;
        }
        unordered_map<string,int> path;//记录到这个单词的路径长度
        queue<string> q;
        q.push(beginWord);
        path[beginWord]=1;
        while(!q.empty()){
            string cur=q.front();
            q.pop();
            for(int i=0;i<cur.length();i++){
                int Path=path[cur];
                for(int k=0;k<26;k++){//列举每一个变换的可能
                    string tmp=cur;
                    tmp[i]='a'+k;
                    if(tmp==endWord)return Path+1;
                    if(word.count(tmp)==1 && path.count(tmp)==0){//在单词集合中存在且没有被加入过
                        path[tmp]=Path+1;
                        q.push(tmp);
                    }
                }
            }
        }
        return 0;
    }
};

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值