题目描述
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 and each intermediate word must exist in the dictionary. For example, given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
One shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog", the program should return its length 5.
java实现
使用bfs进行实现
public class WordLadder {
public static int shortestTransformationLength(Set<String> dict,String start,String end) {
dict.add(end);
LinkedList<WordNode> queue = new LinkedList<WordNode>();
queue.add(new WordNode(start,1));
while (!queue.isEmpty()) {
WordNode wordNode = queue.poll();
if (wordNode.word.equals(end)) {
return wordNode.length;
}
String temp = wordNode.word;
char[] chars = temp.toCharArray();
for (int j = 0; j < chars.length;j ++) {
for (char i = 'a'; i < 'z';i ++) {
if (chars[j] != i) {
char c = chars[j];
chars[j] = i;
String tempStr = new String(chars);
if (dict.contains(tempStr)) {
queue.add(new WordNode(tempStr,wordNode.length + 1));
dict.remove(tempStr);
}
chars[j] = c;
}
}
}
}
return -1;
}
public static class WordNode {
public String word;
public int length;
public WordNode(String word,int length) {
this.word = word;
this.length = length;
}
}
public static void main(String[] args) {
String start = "hit";
String end = "cog";
String[] strs = {"hot","dot","dog","lot","log"};
Set<String> dict = new HashSet<String>();
dict.addAll(Arrays.asList(strs));
System.out.println(shortestTransformationLength(dict,start,end));
}
}