[译]字梯

原文链接: 字梯

给定两个单词(开始和结束)和一个字典,从开始到结束找到最短转换序列的长度,这样只有一个字母可以在一个时间内改变,而每个中间字必须存在于字典中。
例如,给定:

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

一个最短的转换是"hit" -> "hot" -> "dot" -> "dog" -> "cog", 程序应该返回它的长度5。

分析
更新于2015年6月7日
因此,我们很快意识到这是一个搜索问题,并且第一次搜索保证了最优解。


[译]字梯_第1张图片
图1

Java解决

class WordNode{
    String word;
    int numSteps;
 
    public WordNode(String word, int numSteps){
        this.word = word;
        this.numSteps = numSteps;
    }
}
 
public class Solution {
    public int ladderLength(String beginWord, String endWord, Set wordDict) {
        LinkedList queue = new LinkedList();
        queue.add(new WordNode(beginWord, 1));
 
        wordDict.add(endWord);
 
        while(!queue.isEmpty()){
            WordNode top = queue.remove();
            String word = top.word;
 
            if(word.equals(endWord)){
                return top.numSteps;
            }
 
            char[] arr = word.toCharArray();
            for(int i=0; i

你可能感兴趣的:([译]字梯)