跟上一題127一樣,但是額外要求要輸出搜索的路徑,而且是 所有的路徑
所以需要考慮將路徑轉換爲有向圖,然後將有向圖中的最短路徑全部枚舉出來
graph的話我們通過map<string,list<string>>來記錄節點和從節點出發可以到達的其他節點,
class Solution {
public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {
int L = beginWord.length();
// preprocessing for the intermediate words
// the adjacency map provides the adjacent words index for the words in wordList
Map<Integer, List<Integer>> neighbors = new HashMap<>();
List<String> newWordList = new ArrayList<>();
newWordList.add(beginWord);
for (String word : wordList) {
if (!word.equals(beginWord)) {
newWordList.add(word);
}
}
Map<String, Integer> wordDict = new HashMap<>();
for (int i = 0; i < newWordList.size(); i ++) {
wordDict.put(newWordList.get(i), i);
neighbors.put(i, new ArrayList<>());
}
for (int i = 0; i < newWordList.size(); i ++) {
for (int j = 0; j < L; j++) {
char[] chars = newWordList.get(i).toCharArray();
for (char c = 'a'; c <= 'z'; c++) {
chars[j] = c;
String newWord = new String(chars);
if (wordDict.containsKey(newWord) && i != wordDict.get(newWord)) {
List<Integer> adjacencies = neighbors.get(i);
adjacencies.add(wordDict.get(newWord));
}
}
}
}
List<List<String>> result = new ArrayList<>();
// end index
int end = newWordList.indexOf(endWord);
// corner case
if (end == 0 || end == -1) return result;
// bfs
Map<Integer, Integer> ladders = new HashMap<>();
bfs(neighbors, ladders, end);
// dfs
List<String> solution = new ArrayList<>();
dfs(newWordList, neighbors, solution, result, ladders, 0, end);
return result;
}
// breadth first search
private void bfs( Map<Integer, List<Integer>> neighbors, Map<Integer, Integer> ladders, int end) {
Queue<Integer> Q = new LinkedList<>();
boolean reachEnd =false;
Q.add(0);
ladders.put(0, 1);
while (!reachEnd && end != -1 && !Q.isEmpty()) {
int size = Q.size();
for (int i = 0; i < size; i ++) {
Integer cur = Q.poll();
if (cur == end) reachEnd = true;
for (Integer next : neighbors.get(cur)) {
if (!ladders.containsKey(next)) {
Q.add(next);
ladders.put(next, ladders.get(cur) + 1);
}
}
}
}
}
private void dfs(List<String> newWordList, Map<Integer, List<Integer>> neighbors, List<String> solution, List<List<String>> result, Map<Integer, Integer> ladders, int cur, int end) {
solution.add(newWordList.get(cur));
if (cur == end) {
result.add(new ArrayList<>(solution));
} else {
for (int next : neighbors.get(cur)){
if (ladders.containsKey(next) && ladders.get(next) == ladders.get(cur) + 1) {
dfs(newWordList, neighbors, solution, result, ladders, next, end);
}
}
}
solution.remove(solution.size() - 1);
}
}
這個題感覺太難了,
先這樣放着吧,還是126簡單
這個代碼是複製別人提交的東西