[LeetCode]Word Ladder

本文介绍了一个经典的图论问题——单词梯。使用BFS算法解决从一个单词转换为另一个单词的问题,要求每次只能改变一个字母,并且中间形成的单词必须在字典中存在。文章详细解析了算法实现过程及注意事项。

Given two words (beginWord and endWord), and a dictionary, find the length of shortest transformation sequence from beginWord toendWord, such that:

  1. Only one letter can be changed at a time
  2. Each intermediate word must exist in the dictionary

For example,

Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]

As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.

Note:

  • Return 0 if there is no such transformation sequence.
  • All words have the same length.

  • All words contain only lowercase alphabetic characters.
[LeetCode Source]

思路:这个题目要用到BFS,图论的解法。就是无权最短路径问题。

我们从一个点开始搜索,每次扩展一层,直到找到最后的单词。

我们采用两个队列,一个队列存储距离,另一个队列存储单词。

每次遍历到一个点后要将该点从Dict中删除掉,一种方法是遍历Dict找到相邻的点,

第二种是生成一个单词所有相邻单词然后搜寻。第一种方法会超时。

特别注意对Set操作时,如果采用erase会让原来的迭代器失败。比如:

       for(auto it=wordDict.begin();it!=wordDict.end();++it){
                if(next(now,*it)){
                    dis.push(distance+1);
                    q.push(*it);
                    wordDict.erase(it);
                }
            }
这样编译的确通过,但是会出现运行时错误,原因在于erase之后原来迭代次失效了,导致这个循环出错,一定要避免。
最后AC的代码。这个时间依然有点长还可以改进。

class Solution {
public:
    int ladderLength(string beginWord, string endWord, unordered_set<string>& wordDict) {
        queue<string> q;
        q.push(beginWord);
        queue<int> dis;
        dis.push(1);
        wordDict.erase(beginWord);
        while(!q.empty()){
            string now = q.front();
            int distance = dis.front();
            if(now==endWord)
                return distance;
            q.pop();
            dis.pop();
            for(int i=0;i<now.size();++i){
                for(char j='a';j<='z';++j){
                    char rec = now[i];
                    now[i] = j;
                    if(wordDict.find(now)!=wordDict.end())
                    {
                        q.push(now);
                        dis.push(distance+1);
                        wordDict.erase(now);
                    }
                    now[i] = rec;
                }
            }
        }
        return 0;
    }
};


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值