美文网首页
120. Word Ladder

120. Word Ladder

作者: 鸭蛋蛋_8441 | 来源:发表于2019-05-31 14:21 被阅读0次

    Description

    Given two words (start and end), and a dictionary, find the shortest transformation sequence from start to end, output the length of the sequence.

    Transformation rule such that:

    Only one letter can be changed at a time

    Each intermediate word must exist in the dictionary. (Start and end words do not need to appear in the dictionary )

    Return 0 if there is no such transformation sequence.

    All words have the same length.

    All words contain only lowercase alphabetic characters.

    You may assume no duplicates in the word list.

    You may assume beginWord and endWord are non-empty and are not the same.

    Example

    Example 1:

    Input:start = "a",end = "c",dict =["a","b","c"]

    Output:2

    Explanation:

    "a"->"c"

    Example 2:

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

    Output:5

    Explanation:

    "hit"->"hot"->"dot"->"dog"->"cog"

    思路:

    类似于发现一个拓扑排序,起点是start,终点是end,但是不同于一般的拓扑排序,并没有给图的信息,此题需要自己用BFS构建一个有向图,要注意不能出现双向箭头,并且一个层级的点之间没有箭头。一直遍历到出现end点结束。

    刚开始写了个比较方法去比较dict中点与点之间是否满足变换条件,然后每次循环调用,最后会导致超时(下图中是反面例子),借鉴答案用26个字母先得到每个单词的变换集合再去dict中查找会比较有效率。

    代码:

    相关文章

      网友评论

          本文标题:120. Word Ladder

          本文链接:https://www.haomeiwen.com/subject/vmiwtctx.html