【广搜、哈希】| LeetCode 127. 单词接龙

题目描述

字典 wordList 中从单词 beginWord 和 endWord 的 转换序列 是一个按下述规格形成的序列:

序列中第一个单词是 beginWord 。
序列中最后一个单词是 endWord 。
每次转换只能改变一个字母。
转换过程中的中间单词必须是字典 wordList 中的单词。
给你两个单词 beginWord 和 endWord 和一个字典 wordList ,找到从 beginWord 到 endWord 的 最短转换序列 中的 单词数目 。如果不存在这样的转换序列,返回 0。

示例 1:

输入:beginWord = “hit”, endWord = “cog”, wordList = [“hot”,“dot”,“dog”,“lot”,“log”,“cog”]
输出:5
解释:一个最短转换序列是 “hit” -> “hot” -> “dot” -> “dog” -> “cog”, 返回它的长度 5。

示例 2:

输入:beginWord = “hit”, endWord = “cog”, wordList = [“hot”,“dot”,“dog”,“lot”,“log”]
输出:0
解释:endWord “cog” 不在字典中,所以无法进行转换。

提示:

  1. 1 <= beginWord.length <= 10
  2. 1 <= wordList.length <= 5000
  3. beginWord、endWord 和 wordList[i] 由小写英文字母组成
  4. beginWord != endWord
  5. wordList 中的所有字符串 互不相同
  6. beginWord不用在字典中,而endWord要在字典中

代码实现

1. 广搜+哈希

class Solution {
	public:
        int ladderLength(string bwrd, string ewrd, vector<string>& words) {
            for (int i=0;i<words.size();i++) hash[words[i]]=false;
            if (!hash.count(ewrd)) return 0;
            int len=bwrd.length();
            q.push({ewrd,1});
            hash[ewrd]=true;
            while (q.size()) {
                PSI t=q.front();
                q.pop();
                string s=t.first,ss;
                int cnt=t.second;
                for (int i=0;i<len;i++) {
                    ss=s;
                    for (char ch='a';ch<='z';ch++) {
                        if (s[i]==ch) continue;
                        ss[i]=ch;
                        if (ss==bwrd) return cnt+1;
                        if (hash.count(ss) && !hash[ss]) q.push({ss,cnt+1}),hash[ss]=true;
                    }
                }
            }
            return 0;
        }
	private:
        unordered_map<string,bool> hash;
        typedef pair<string,int> PSI;
        queue<PSI> q;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值