题目要求:
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 intermediate word must exist in the word list
For example,
Given:
beginWord = “hit”
endWord = “cog”
wordList = [“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.
解题思路
可以看做是一张简单图:每个点是wordList中的一个单词,点的相邻点是改变一个字母得到的单词,起点和终点则分别是startWord和endWord,找寻起点到终点的最短路径:
找寻最短路径,考虑使用BFS,一层一层遍历,每一层到起点的distance即为起点单词变到当前单词的路径长度,如hit起点层为1,hot层为2,dot与lot层为3,到最后终点层cog为5,则最短转化路径长度为5。
- 利用队列存储点,进行BFS
- 利用hashSet存储已经遍历过的点。如hot的相邻点为dot与lot,存入hash与队列,dot的相邻点为lot、hot与dog,但lot,hot都已在hash中(队列中)了,因此接下来只需遍历dog即可。
代码
public class Solution {
public int ladderLength(String beginWord, String endWord, Set<String> wordList) {
if(wordList == null ) return 0;
if(beginWord == endWord) return 1;
wordList.add(beginWord);
wordList.add(endWord);
HashSet<String> hash = new HashSet<String>();
Queue<String> queue = new LinkedList<String>();
queue.offer(beginWord);
hash.add(beginWord);
int length = 1;
//BFS遍历整张图
while(!queue.isEmpty()){
//length记录起点到终点的路径,每遍历一层+1
length++;
int size = queue.size();
for (int i = 0; i < size; i++) {
String word = queue.poll();
//将当前点的未被遍历过的邻居点加入队列
for(String next:getNextWords(word,wordList)){
if(next.equals(endWord)) return length;
if(!hash.contains(next)){
queue.offer(next);
hash.add(next);
}
}
}
}
return 0;
}
//获得一个点的相邻点,即一个词改变一个字母能得到的在wordList中的词
public List<String> getNextWords(String word,Set<String> wordList){
ArrayList<String> nextWords = new ArrayList<String>();
for (char c = 'a'; c <= 'z'; c++) {
for (int i = 0; i < word.length(); i++) {
if (c == word.charAt(i)) {
continue;
}
String nextWord = replace(word, i, c);
if (wordList.contains(nextWord)) {
nextWords.add(nextWord);
}
}
}
return nextWords;
}
private String replace(String s, int index, char c) {
char[] chars = s.toCharArray();
chars[index] = c;
return new String(chars);
}
}