Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence 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"]
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.
- You may assume no duplicates in the word list.
- You may assume beginWord and endWord are non-empty and are not the same.
UPDATE (2017/1/20):
The wordList parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.
思路:广度优先搜索,注意搜索到的词:
1.必须是在列表中出现,否则不合理
2.已搜索过的词不应该再被搜索,否则会出现相互转化,比如abc -> abd -> abc
3.将参数列表的list转化为set,提高搜索速度(否则会超时)
4.如果endword压根就是不合理的,即搜索不到,则直接返回0
public int ladderLength1(String beginWord, String endWord, List<String> wordLists) {
// 广度优先搜索,从开始集(根)、结束集(叶子)两端搜索
// 结束的条件是:当先搜索到的词在结束集中出现
// 对于已经访问过的词,不应该在访问一次,因为会出现二者相互跳转的情况
// 所以对于搜索到的词,判断条件是未被访问过且是合理的(出现在wordList中)
if (!wordLists.contains(endWord))
return 0;// 如果endWord本身就是不合理的,返回0
int res = 1;// 记录树深度,因为示例里将startword也算作一次,所以初值为1
HashSet<String> begin = new HashSet<String>();// 开始集,初始是bfs树根所在的层,初值为beginword
HashSet<String> end = new HashSet<String>();// 结束集,bfs树叶子节点坐在层,初值是endword
HashSet<String> visited = new HashSet<String>();// 记录访问过的且是合理的(在wordList中出现)词
HashSet<String> wordList = new HashSet<String>();
for (String s : wordLists) {
wordList.add(s);
}
begin.add(beginWord);
end.add(endWord);
while (!begin.isEmpty() && !end.isEmpty()) {
if (begin.size() > end.size()) {// 为了使开始与结束的两端更为接近,加快搜索速度(源自leetcode答案)
HashSet<String> t = begin;
begin = end;
end = t;
}
HashSet<String> temp = new HashSet<String>();// 保存可放入开始集的新拓展的bfs树中下一层的词
for (String word : begin) {
char[] chars = word.toCharArray();
for (int i = 0; i < word.length(); i++) {// 穷举各个位置的情况
for (char ch = 'a'; ch <= 'z'; ch++) {// 穷举各个可能出现的字母
char old = chars[i];
chars[i] = ch;
String terget = String.valueOf(chars);
if (end.contains(terget))
return 1 + res;// 搜索到答案
if (!visited.contains(terget) && wordList.contains(terget)) {// 未被搜索过且是合理的
visited.add(terget);
temp.add(terget);
}
chars[i] = old;// 恢复成原样
}
}
}
res++;// 所搜的bfs深度+1
begin = temp;// 更新开始层次,从下一层开始
}
return 0;// 未找到endWord
}