leetcode笔记: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 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.

二. 题目分析

参考链接:http://www.mamicode.com/info-detail-448603.html

可以将这道题看成是一个图的问题。我们将题目映射到图中,顶点是每个字符串,然后两个字符串如果相差一个字符则进行连边。我们的字符集只有小写字母,而且字符串的长度固定,假设是L。那么可以注意到每一个字符可以对应的边有25个(26个小写字母去掉自己),那么一个字符串可能存在的边是25*L条。接下来就是检查这些对应的字符串是否在字典内,就可以得到一个完整的图的结构。根据题目要求,等价于求这个图中一个顶点到另一个顶点的最短路径,我们一般用BFS广度优先。

这道题,我们只能用最简单的办法去做,每次改变单词的一个字母,然后逐渐搜索,这种求最短路径,树最小深度问题用BFS最合适。

和当前单词相邻的单词,就是和顶点共边的另一个顶点,是对当前单词改变一个字母且在字典内存在的单词。

找到一个单词的相邻单词,加入BFS队列后,我们要从字典内删除,因为不删除会造成类似hog->hot->hog这样的死循环。而且删除对求最短路径没有影响,因为我们第一次找到的单词肯定是最短路径,我们是层序遍历去搜索的,最早找到的一定是最短路径,即使后面的其他单词也能转换成它,路径肯定不会比当前的路径短。这道题仅要求求出最短路径长度,不需要求输出最短路径,所以可以删除这个单词。

BFS队列之间用空串”“来标示层与层的间隔,每次碰到层的结尾,遍历深度+1,进入下一层。

三. 示例代码

class Solution {
public:
    int ladderLength(string start, string end, unordered_set<string> &dict) {
        if(start.size() == 0 || end.size() == 0) return 0;

        queue<string> wordQ;
        wordQ.push(start);
        wordQ.push("");
        int path = 1;

        while(!wordQ.empty())
        {
            string str = wordQ.front();
            wordQ.pop();

            if(str != "")
            {
                int len = str.size();
                for(int i = 0; i < len; i++)
                {
                    char tmp = str[i];

                    for(char c = ‘a‘; c <= ‘z‘; c++)
                    {
                        if(c == tmp) continue;
                        str[i] = c;
                        if(str == end) return path + 1; //如果改变后的单词等于end 返回path+1
                        if(dict.find(str) != dict.end())
                        {
                            wordQ.push(str);
                            dict.erase(str);   //字典内删除这个词 防止反复走
                        }
                    }
                    str[i] = tmp;  //重置回原来的单词
                }
            }
            else if(!wordQ.empty())
            {
                //到达当前层的结尾,并且不是最后一层的结尾
                path++;
                wordQ.push("");
            }
        }
        return 0;
    }
};
时间: 2024-08-24 09:02:24

leetcode笔记:Word Ladder的相关文章

LeetCode OJ - Word Ladder 2

我发现在leetcode上做题,当我出现TLE问题时,往往是代码有漏洞,有些条件没有考虑到,这道题又验证了我这一想法. 这道题是在上一道的基础上进一步把所有可能得转换序列给出. 同样的先是BFS,与此同时需要一个hashMap记录下每个节点,和他所有父节点的对应关系,然后通过DFS,回溯所有可能的路径. 下面是AC代码. 1 /** 2 * Given two words (start and end), and a dictionary, find all shortest transform

LeetCode OJ - Word Ladder

我觉得这道题比较难,主要是因为对于我来说: 1. 我没有把这个问题联想到树的宽度遍历(即便没有考虑树的宽度遍历,也是可以做的,但是我一开始实现的代码却是深度遍历,后来发现树的BFS一般使用queue实现的,貌似没有递归的方法??) 2. 即使在意识到用BFS,却还有一个陷阱:我是对字典进行了BFS,这个说实话,代码长,还TLE: 后来参考了前辈的代码,采用对26个单词进行枚举,才解决了这个问题. 下面是AC代码: 1 /** 2 * Given two words (start and end)

[LeetCode] 126. Word Ladder II_Hard tag: BFS&amp;DFS

Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that: Only one letter can be changed at a time Each transformed word must exist in the word list. Note

【LeetCode】Word Ladder 字符串

题目:Word Ladder <span style="font-size:18px;">/**LeetCode word ladder * 题目:给定一个起始单词和一个终结单词以及一个字典,要求每次变换一个字符,成为字典中新的词,直到变为最后的词,要求其最短路径 * 思路:利用队列,先弹出第一个词,分别将词中每一个字符替换直到找到一个字典中存在的词,加入队列,直到匹配的词是最后一个,此时终止 * 如果没有这样的路径,则返回0 */ package javaTrain; i

[LeetCode][JavaScript]Word Ladder

https://leetcode.com/problems/word-ladder/ Word Ladder Given two words (beginWord and endWord), and a dictionary, find the length of shortest transformation sequence from beginWord to endWord, such that: Only one letter can be changed at a time Each

[Leetcode][JAVA] Word Ladder II

Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) 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

Leetcode 127. Word Ladder

思路: 1 class Solution(object): 2 def __init__(self): 3 return 4 5 def ladderLength(self, beginWord, endWord, wordList): 6 """ 7 :type beginWord: str 8 :type endWord: str 9 :type wordList: List[str] 10 :rtype: int 11 """ 12 fro

[Leetcode][JAVA] 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

leetcode 127. Word Ladder ----- java

Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that: Only one letter can be changed at a time Each intermediate word must exist in the word li

leetcode 126. Word Ladder II

1 import string 2 import collections 3 4 class Solution(object): 5 def findLadders(self, begin, end, words_list): 6 '''删除起至单词''' 7 words_list.discard(begin) 8 words_list.discard(end) 9 10 '''根据tree递归构造路径''' 11 def construct_paths(source, dest, tree):