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 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
|
class Solution { public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) { Map<String, List<String>> graph = buildGraph(beginWord, endWord, wordList); List<List<String>> ans = new LinkedList<>(); System.out.println(graph); List<String> l = new LinkedList<>(); dfs(graph, beginWord, endWord, ans, l); return ans; } private void dfs(Map<String, List<String>> graph, String word, String endWord, List<List<String>> ans, List<String> l){ if(word.equals(endWord)){ l.add(word); ans.add(new LinkedList<>(l)); l.remove(l.size()-1); return; } if(!graph.containsKey(word)){ return; } List<String> tmp = graph.get(word); l.add(word); for(String t:tmp){ dfs(graph, t, endWord, ans, l); } l.remove(l.size()-1); } private Map<String, List<String>> buildGraph(String beginWord, String endWord, List<String> wordList){ Set<String> set = new HashSet<>(wordList); Map<String, List<String>> graph = new HashMap<>(); Queue<String> queue = new LinkedList<>(); queue.offer(beginWord); set.remove(beginWord); boolean finished = false; while(!queue.isEmpty() && finished==false){ int size = queue.size(); Set<String> visited = new HashSet<>(); while(size>0){ String word = queue.poll();
for(int i =0;i<=word.length()-1;i++){ for(char c = 'a';c<='z';c++){ if(c==word.charAt(i)) continue; String newWord = word.substring(0, i) + c + word.substring(i+1); if(newWord.equals(endWord)){ finished = true; } List<String> neighbors = new LinkedList<>(); if(graph.containsKey(word)){ neighbors = graph.get(word); } if(set.contains(newWord)){ neighbors.add(newWord); graph.put(word, neighbors); } if(set.contains(newWord)&&!visited.contains(newWord)){ queue.offer(newWord); } visited.add(newWord); } } size--; } set.removeAll(visited); } return graph; } }
|