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
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.
题不难理解,输入的是:一个单词和一个字典,单词每次只允许改变一个字母变成字典中的某个单词,如此循环,判断是否能变成目标单词,如果能的话返回变换次数,否则返回0。
解题报告:
最直观的思路就是DFS,每次变成字典中的某个新单词,同时从字典中删除这个单词然后不断递归。
大数据时候超时。因为要求的是最短的变换次数,所以可以使用BFS,和DFS不一样不一次走到最深。逐层遍历变换了一次、二次、三次、n次的所有单词。
思考一下DFS和BFS的区别,举个最简单的例子,111 -> 311。
DFS的话,111->112,之后需要DFS 112的所有变形。同理111->113之后还要遍历113的所有变形。
上AC代码:
Only one letter can be changed at a time
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.
题不难理解,输入的是:一个单词和一个字典,单词每次只允许改变一个字母变成字典中的某个单词,如此循环,判断是否能变成目标单词,如果能的话返回变换次数,否则返回0。
解题报告:
最直观的思路就是DFS,每次变成字典中的某个新单词,同时从字典中删除这个单词然后不断递归。
大数据时候超时。因为要求的是最短的变换次数,所以可以使用BFS,和DFS不一样不一次走到最深。逐层遍历变换了一次、二次、三次、n次的所有单词。
思考一下DFS和BFS的区别,举个最简单的例子,111 -> 311。
DFS的话,111->112,之后需要DFS 112的所有变形。同理111->113之后还要遍历113的所有变形。
而BFS的话, 111
112 113 121 131 211 311
只需要6次就能找到最终结果。
上AC代码:
public class Solution {
public int ladderLength(String start, String end, HashSet<String> dict) {
if(start.equals(end)==true||start==null||end==null) {
return 0;
}
Queue queue = new LinkedList<String>();
//记录当前节点所在的层数,也就是经过了多少次变换
LinkedList<Integer> distanceQueue = new LinkedList<Integer>();
queue.add(start);
distanceQueue.add(1);
int ret = 0;
while(!queue.isEmpty()) {
String str = (String)queue.poll();
ret = (int)distanceQueue.poll();
//对当前单词的每个字符逐个测试,生成的新单词是否存在于字典中
for(int i=0; i<str.length(); i++){
char[] strCharArr = str.toCharArray();
for(char c='a'; c<='z'; c++){
strCharArr[i] = c;
String newWord = new String(strCharArr);
if(dict.contains(newWord)){
if(newWord.equals(end)) {
return ret + 1;
}
queue.add(newWord);
distanceQueue.add(ret + 1);
dict.remove(newWord);
}
}
}
}
return 0;
}
}