题目:
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.
由于只需要求最短的距离,所以直接BFS就行了。这题OJ的数据卡得比较严,裸BFS会TLE。没有必要写双向的BFS,注意下剪枝就可以了。直接放代码。
code:
import java.util.*;
public class WordLadder {
public int ladderLength(String beginWord, String endWord, Set<String> wordList) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
LinkedList<String> queue = new LinkedList<String>();
queue.offer(beginWord);
map.put(beginWord, 1);
boolean flag = false;
while(!queue.isEmpty()){
String curr = queue.poll();
for(String next : getNextWords(curr, wordList)){
if(next.equals(endWord)){
flag = true;
map.put(next, map.get(curr) + 1);
System.out.println(next + " " + map.get(next));
return map.get(next);
}
if(wordList.contains(next)){
if(!map.containsKey(next)){
map.put(next, map.get(curr) + 1);
System.out.println(next + " " + map.get(next));
queue.offer(next);
}
}
}
}
if(flag) return map.get(endWord);
else return 0;
}
public List<String> getNextWords(String word, Set<String> wordList){
List<String> nextWords = new ArrayList<String>();
for(int i = 0; i < word.length(); i++){
for(char c = 'a'; c <= 'z'; c++){
if(c == word.charAt(i)) continue;
char[] arr = word.toCharArray();
arr[i] = c;
String next = new String(arr);
if(wordList.contains(next)) nextWords.add(next);
}
}
return nextWords;
}
public static void main(String[] args){
WordLadder WL = new WordLadder();
Set<String> wordList = new HashSet<String>();
wordList.add("a");
wordList.add("b");
wordList.add("c");
String beginWord = "a";
String endWord = "c";
int result = WL.ladderLength(beginWord, endWord, wordList);
System.out.println(result);
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。