今天的題目為127.Word Ladder,從單字beginWord到endWord的轉換序列是一串單字[beginWord -> s1 -> s2 -> ... ->sk],需滿足以下條件:每一對相鄰單字只相差一個字母,每個 si(1 ≤ i ≤ k)都必須在字典 wordList 中,beginWord 不需要在 wordList 中,最後一個單字 sk 必須是 endWord,回傳最短轉換序列中的單字數量(包含beginWord和 endWord),如果不存在這樣的序列,則回傳 0。
以下為程式碼:
class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
Set<String> wordSet = new HashSet<>(wordList);
if (!wordSet.contains(endWord)) return 0;
Queue<String> queue = new LinkedList<>();
queue.offer(beginWord);
int level = 1;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
String word = queue.poll();
char[] chars = word.toCharArray();
for (int j = 0; j < chars.length; j++) {
char original = chars[j];
for (char c = 'a'; c <= 'z'; c++) {
if (c == original) continue;
chars[j] = c;
String newWord = new String(chars);
if (newWord.equals(endWord)) return level + 1;
if (wordSet.contains(newWord)) {
queue.offer(newWord);
wordSet.remove(newWord);
}
}
chars[j] = original;
}
}
level++;
}
return 0;
}
}