1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
| package com.demo.s126;
import java.util.*;
public class Solution { public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) { List<List<String>> res = new ArrayList<>(); Set<String> dict = new HashSet<>(wordList); if (!dict.contains(endWord)) { return res; }
dict.remove(beginWord);
Map<String, Integer> steps = new HashMap<>(); steps.put(beginWord, 0); Map<String, List<String>> from = new HashMap<>(); int step = 1; boolean found = false; int wordLen = beginWord.length(); Queue<String> queue = new LinkedList<>(); queue.offer(beginWord); while (!queue.isEmpty()) { int size = queue.size(); for (int i = 0; i < size; i++) { String currWord = queue.poll(); char[] charArray = currWord.toCharArray(); for (int j = 0; j < wordLen; j++) { char origin = charArray[j]; for (char c = 'a'; c <= 'z'; c++) { charArray[j] = c; String nextWord = String.valueOf(charArray); if (steps.containsKey(nextWord) && step == steps.get(nextWord)) { from.get(nextWord).add(currWord); } if (!dict.contains(nextWord)) { continue; } dict.remove(nextWord); queue.offer(nextWord);
from.putIfAbsent(nextWord, new ArrayList<>()); from.get(nextWord).add(currWord); steps.put(nextWord, step); if (nextWord.equals(endWord)) { found = true; } } charArray[j] = origin; } } step++; if (found) { break; } }
if (found) { Deque<String> path = new ArrayDeque<>(); path.add(endWord); dfs(from, path, beginWord, endWord, res); } return res; }
public void dfs(Map<String, List<String>> from, Deque<String> path, String beginWord, String cur, List<List<String>> res) { if (cur.equals(beginWord)) { res.add(new ArrayList<>(path)); return; } for (String precursor : from.get(cur)) { path.addFirst(precursor); dfs(from, path, beginWord, precursor, res); path.removeFirst(); } }
}
|