题目地址: https://leetcode.com/problems/word-ladder-ii/
Given two words (beginWord and endWord), and a dictionary’s word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:
1. Only one letter can be changed at a time.
2. Each transformed word must exist in the word list.
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.
Example 1:
Input:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]
Output:
[
["hit","hot","dot","dog","cog"],
["hit","hot","lot","log","cog"]
]
Example 2:
Input:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]
Output: []
Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.
给定两个单词(beginWord 和 endWord)和一个字典 wordList,找出所有从 beginWord 到 endWord 的最短转换序列。转换需遵循如下规则:
1. 每次转换只能改变一个字母。
2. 转换过程中的中间单词必须是字典中的单词。
说明:
* 如果不存在这样的转换序列,返回 0。
* 所有单词具有相同的长度。
* 所有单词只由小写字母组成。
* 字典中不存在重复的单词。
* 你可以假设 beginWord 和 endWord 是非空的,且二者不相同。
class Solution {
public List> findLadders(String beginWord, String endWord, List wordList) {
Map checked = new HashMap<>();
for (int i = 0; i < wordList.size(); i++) {
checked.put(wordList.get(i), 0);
}
List> res = new ArrayList<>();
if (checked.get(endWord) == null) return res;
List list = new ArrayList<>();
list.add(beginWord);
res.add(list);
checked.put(beginWord, 1);
int level = 1;
while (res.size() > 0) {
boolean flag = false;
int count = res.size();
level++;
for (int i = 0; i < count; i++) {
List cur = res.remove(0);
char[] lastArr = cur.get(cur.size() - 1).toCharArray();
for (int j = 0; j < lastArr.length; j++) {
char ch = lastArr[j];
for (char k = 'a'; k <= 'z'; k++) {
if (ch == k) continue;
lastArr[j] = k;
String temp = String.valueOf(lastArr);
Integer pre = checked.get(temp);
if (pre == null || (pre > 0 && pre < level)) continue;
List tempList = new ArrayList<>(cur);
tempList.add(temp);
checked.put(temp, level);
res.add(tempList);
if (temp.equals(endWord)) {
flag = true;
}
}
lastArr[j] = ch;
}
}
if (flag) {
for (int i = 0; i < res.size(); i++) {
if (!endWord.equals(res.get(i).get(res.get(i).size() - 1))) {
res.remove(i);
i--;
}
}
break;
}
}
return res;
}
}
执行耗时:411 ms,击败了50.59% 的Java用户
内存消耗:46.9 MB,击败了20.71% 的Java用户