-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWordLadderIII.java
More file actions
73 lines (67 loc) · 2.38 KB
/
WordLadderIII.java
File metadata and controls
73 lines (67 loc) · 2.38 KB
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
import java.util.*;
public class WordLadderIII {
public List<String> findLadder(String beginWord, String endWord, List<String> wordList) {
List<String> res = new ArrayList<>();
Set<String> wordDict = new HashSet<>(wordList);
if (!wordDict.contains(endWord)) {
return res;
}
Queue<String> queue = new LinkedList<>();
queue.offer(beginWord);
Map<String, String> graph = new HashMap<>();
boolean found = false;
while (!queue.isEmpty()) {
int sz = queue.size();
while (sz-- > 0) {
String cur = queue.poll();
List<String> nexts = transform(cur, wordDict);
for (String next: nexts) {
graph.put(next, cur);
if (wordDict.remove(next)) {
queue.offer(next);
}
if (next.equals(endWord)) {
return getPath(graph, endWord, beginWord);
}
}
}
}
return res;
}
private List<String> getPath(Map<String, String> graph, String start, String target) {
List<String> path = new LinkedList<>();
String cur = start;
while (!cur.equals(target)) {
path.add(0, cur);
cur = graph.get(cur);
}
path.add(0, cur);
return path;
}
private List<String> transform(String word, Set<String> wordDict) {
List<String> res = new ArrayList<>();
char[] chars = word.toCharArray();
for (int i = 0; i < chars.length; i++) {
char orig = chars[i];
for (char ch = 'a'; ch <= 'z'; ch++) {
if (ch == orig) {
continue;
}
chars[i] = ch;
String next = String.valueOf(chars);
if (wordDict.contains(next)) {
res.add(next);
}
}
chars[i] = orig;
}
return res;
}
public static void main(String[] args) {
WordLadderIII sol = new WordLadderIII();
List<String> res = sol.findLadder("hit", "cog", Arrays.asList("hot","dot","dog","lot","log","cog"));
Utils.printList(res);
res = sol.findLadder("hit", "cog", Arrays.asList("hot","dot", "lot","log","cog"));
Utils.printList(res);
}
}