Word Ladder

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

  1. Only one letter can be changed at a time
  2. 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.

 

三种方法:DFS, BFS, Dijkstra

Finding minimum depth with BFS is faster than that with DFS since we don't need to check all possible paths. The first time when we hits the goal in BFS, we know the current depth is the minimum depth.

Improve algrithm by remove visited word from dict, so need to keep a hashMap for visited words.

多次访问且dict不太变的话用Dijkstra比较快,因为一次计算完所有的edge

public class Solution {
    public int ladderLength(String start, String end, Set<String> dict) {
        LinkedList<String> words=new LinkedList<String>();
        LinkedList<Integer> distance=new LinkedList<Integer>();
        words.add(start);
        distance.add(1);
        
        while(!words.isEmpty()){
            String curWord=words.pop();
            int curDis=distance.pop();
            if(curWord.equals(end)){
                return curDis;
            }   
            for(int i=0;i<curWord.length();i++){
                char[] temp=curWord.toCharArray();
                for(char c='a';c<='z';c++){
                    temp[i]=c;
                    String newWord=new String(temp); 
                    if(dict.contains(newWord)){
                    words.add(newWord);
                    distance.add(curDis+1);
                    dict.remove(newWord);
                    }
                }
            }
        }
        return 0;
    }
}

 

posted on 2014-06-30 13:59  青椰子  阅读(165)  评论(0)    收藏  举报

导航