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.
Solution1.1:
思路: BFS + wordList搜索
Time Complexity: O(wordList_size * wordList_size * word_len) Space Complexity: O(N)
Solution1.2:
思路: BFS + for(length for(a-z)) 搜索
// 实现:这里没有提前建图,而是on the fly边建图(建neighbors) 边找
Time Complexity: O(wordList_size * word_len * 24) Space Complexity: O(N)
Solution1.1 Code:
class Solution1.1 Round1.1 {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
int count = 0;
boolean[] used = new boolean[wordList.size()];
Queue<String> queue = new LinkedList<>();
queue.offer(beginWord);
while(!queue.isEmpty()) {
count++;
int queue_size = queue.size();
for(int i = 0; i < queue_size; i++) {
String src_str = queue.poll();
// found matched
if(src_str.equals(endWord)) {
return count;
}
// not found: keep doing bfs
for(int index = 0; index < wordList.size(); index++) {
String dst_str = wordList.get(index);
if(used[index] == false && calc_dist(src_str, dst_str) == 1) {
queue.offer(dst_str);
used[index] = true;
}
}
}
}
return 0;
}
private int calc_dist(String a, String b) {
int dist = 0;
for(int i = 0; i < a.length(); i++) {
if(a.charAt(i) != b.charAt(i)) {
dist++;
}
}
return dist;
}
}
Solution1.2 Code:
class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
if(beginWord == null || beginWord.length() == 0 || endWord == null || endWord.length() == 0) return 0;
if(beginWord.length() != endWord.length()) return 0;
Queue<String> queue = new LinkedList<>();
Set<String> word_set = new HashSet<>();
for(String str: wordList) {
word_set.add(str);
}
if (!word_set.contains(endWord)) return 0;
int level = 0 + 1;
queue.offer(beginWord);
while(!queue.isEmpty()) {
level++;
int queue_size = queue.size();
for(int n = 0; n < queue_size; n++) {
String str = queue.poll();
char[] str_arr = str.toCharArray();
for(int pos = 0; pos < str_arr.length; pos++) {
char save = str_arr[pos];
for(char c = 'a'; c <= 'z'; c++) {
str_arr[pos] = c;
String new_str = String.valueOf(str_arr);
if(word_set.contains(new_str)) {
if(new_str.equals(endWord)) {
return level;
}
queue.offer(new_str);
word_set.remove(new_str);
}
}
str_arr[pos] = save;
}
}
}
return 0;
}
}