word-ladder

【题目描述】Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:
Only one letter can be changed at a time
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 length5.
Note:
Return 0 if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.

【解题思路】这种题,肯定是每次改变单词的一个字母,然后逐渐搜索,很多人一开始就想到用dfs,其实像这种求最短路径、树最小深度问题bfs最适合,可以参考我的这篇博客bfs(层序遍历)求二叉树的最小深度。本题bfs要注意的问题:
和当前单词相邻的单词是:对当前单词改变一个字母且在字典中存在的单词
找到一个单词的相邻单词,加入bfs队列后,要从字典中删除,因为不删除的话会造成类似于hog->hot->hog的死循环。而删除对求最短路径没有影响,因为我们第一次找到该单词肯定是最短路径,即使后面其他单词也可能转化得到它,路径肯定不会比当前的路径短(如果要输出所有最短路径,则不能立即从字典中删除,具体见下一题)
bfs队列中用NULL来标识层与层的间隔,每次碰到层的结尾,遍历深度+1

【考查内容】数组,查找,宽度搜索

class Solution {
public:
    int ladderLength(string start, string end, unordered_set<string> &dict) {
        //BFS遍历找到的第一个匹配就是最短转换,空字符串是层与层之间的分隔标志
        queue<string> Q;
        Q.push(start); Q.push("");
        int res = 1;
        while(Q.empty() == false){
            string str = Q.front();
            Q.pop();
            if(str != ""){
                int strLen = str.length();
                for(int i = 0; i < strLen; i++){
                    char tmp = str[i];
                    for(char c = 'a'; c <= 'z'; c++){
                        if(c == tmp)
                            continue;
                        str[i] = c;
                        if(str == end)
                            return res+1;
                        if(dict.find(str) != dict.end()){
                            Q.push(str);
                            dict.erase(str);
                        }
                    }
                    str[i] = tmp;
                }
            }
            else if(Q.empty() == false){//到达当前层的结尾,并且不是最后一层的结尾
                res++;
                Q.push("");
            }
        }
        return 0;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值