资讯专栏INFORMATION COLUMN

leetcode126. Word Ladder II

cooxer / 2838人阅读

摘要:题目要求相比于,要求返回所有的最短路径。至于如何生成该有向图,则需要通过广度优先算法,利用队列来实现。将每一层的分别入栈。如果遇到则至该层结尾广度优先算法结束。通过这种方式来防止形成圈。

题目要求
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 that beginWord is not a transformed word.
For example,

Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log","cog"]
Return
  [
    ["hit","hot","dot","dog","cog"],
    ["hit","hot","lot","log","cog"]
  ]
Note:
Return an empty list 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.
Yo

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

相比于Word Ladder I,II要求返回所有的最短路径。

思路与代码

在继续往下看之前,请先参考I的这篇博客
首先我们再来查看一下题目中的例子。其实我们可以将路径化为有向图,然后将有向图中从beginWord至endWord的最短路径全部枚举出来。这里需要考虑最合适的数据结构。graph的话我们通过Map>来记录节点和从该节点出发可以到达的其它节点。在题中的含义也就是s1所能转换的所有s2。至于如何生成该有向图,则需要通过广度优先算法,利用队列来实现。将每一层的string分别入栈。如果遇到endWord则至该层结尾广度优先算法结束。

这里有一个可以提高的计算效率的数据结构。在一开始,我通过一个list来记录所有上层已经遍历过的string。通过这种方式来防止形成圈。但是这样的形式造成的代码的超时,所以换成了Map来记录String的最低层数。

    public List> findLadders(String beginWord, String endWord, List wordList) {
        
        Map ladder = new HashMap();
        for(int i = 0 ; i q = new LinkedList();
        int minStep = Integer.MAX_VALUE;
        if(beginWord!=null){
            q.offer(beginWord);
            while(!q.isEmpty()){
                String current = q.poll();
                int step = ladder.get(current)+1;
                if(step>minStep) break;
                for (int i = 0; i < current.length(); i++){
                    StringBuilder sb = new StringBuilder(current);
                    for (char ch="a";  ch <= "z"; ch++){
                        sb.setCharAt(i, ch);
                        String sbs = sb.toString();
                        if(ladder.containsKey(sbs)){
                            if(step>ladder.get(sbs)) continue;
                            else if(step list= new HashSet();
                                list.add(sbs);
                                map.put(current,list);
                            }
                            if(sbs.equals(endWord)) minStep = step;
                        }
                    }
                }
            }
        }
        
        generatePath(beginWord, endWord, new ArrayList());
        return result;
    }
    public void generatePath(String currentWord, String endWord, List current){
        current.add(currentWord);
        if(currentWord.equals(endWord)){
            result.add(new ArrayList(current));
        }else{
            Set set = map.get(currentWord);
            if(set!=null){
                for(String s : set){
                    generatePath(s, endWord,current);
                }    
            }    
        }
        current.remove(current.size()-1);
    }


想要了解更多开发技术,面试教程以及互联网公司内推,欢迎关注我的微信公众号!将会不定期的发放福利哦~

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/67615.html

相关文章

  • [LeetCode] 126. Word Ladder II

    摘要:存放过程中的所有集合为所有的结尾,则顺序存放这个结尾对应的中的所有存放同一个循环的新加入的,在下一个循环再依次对其中元素进行进一步的把首个字符串放入新,再将放入,并将键值对放入,进行初始化 Problem Given two words (start and end), and a dictionary, find all shortest transformation sequenc...

    wayneli 评论0 收藏0
  • 126. Word Ladder II

    题目:Given two words (beginWord and endWord), and a dictionarys word list, find all shortest transformation sequence(s) from beginWord to endWord, such that: Only one letter can be changed at a timeEach...

    Tangpj 评论0 收藏0
  • [Leetcode] Word Ladder 单词爬梯

    摘要:另外,为了避免产生环路和重复计算,我们找到一个存在于字典的新的词时,就要把它从字典中移去。代码用来记录跳数控制来确保一次循环只计算同一层的节点,有点像二叉树遍历循环这个词从第一位字母到最后一位字母循环这一位被替换成个其他字母的情况 Word Ladder Given two words (beginWord and endWord), and a dictionary, find t...

    pinecone 评论0 收藏0
  • leetcode127. Word Ladder

    摘要:但是这种要遍历所有的情况,哪怕是已经超过最小操作次数的情况,导致代码超时。其实从另一个角度来说,这道题可以看做是广度优先算法的一个展示。按上文中的题目为例,可以将广度优先算法写成以下形式。 题目要求 Given two words (beginWord and endWord), and a dictionarys word list, find the length of short...

    Galence 评论0 收藏0
  • [LeetCode/LintCode] Word Ladder

    摘要:使用,利用其按层次操作的性质,可以得到最优解。这样可以保证这一层被完全遍历。每次循环取出的元素存为新的字符串。一旦找到和相同的字符串,就返回转换序列长度操作层数,即。 Problem Given two words (start and end), and a dictionary, find the length of shortest transformation sequence...

    张金宝 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<