-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathWord Ladder II.java
105 lines (84 loc) · 3.54 KB
/
Word Ladder II.java
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
class Solution {
public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {
Set<String> dict = new HashSet(wordList);
if( !dict.contains(endWord) )
return new ArrayList();
// adjacent words for each word
Map<String,List<String>> adjacency = new HashMap();
Queue<String> queue = new LinkedList();
// does path exist?
boolean found = false;
// BFS for shortest path, keep removing visited words
queue.offer(beginWord);
dict.remove(beginWord);
while( !found && !queue.isEmpty() ) {
int size = queue.size();
// adjacent words in current level
HashSet<String> explored = new HashSet();
while( size-- > 0 ) {
String word = queue.poll();
if( adjacency.containsKey(word) )
continue;
// remove current word from dict, and search for adjacent words
dict.remove(word);
List<String> adjacents = getAdjacents(word, dict);
adjacency.put(word, adjacents);
for(String adj : adjacents) {
if( !found && adj.equals(endWord) )
found = true;
explored.add(adj);
queue.offer(adj);
}
}
// remove words explored in current level from dict
for(String word : explored)
dict.remove(word);
}
// if a path exist, dfs to find all the paths
if( found )
return dfs(beginWord, endWord, adjacency, new HashMap());
else
return new ArrayList();
}
private List<String> getAdjacents(String word, Set<String> dict) {
List<String> adjs = new ArrayList();
char[] wordChars = word.toCharArray();
for(int i=0; i<wordChars.length; i++)
for(char c='a'; c<='z'; c++) {
char temp = wordChars[i];
wordChars[i] = c;
String newAdj = new String(wordChars);
if( dict.contains(newAdj) )
adjs.add(newAdj);
wordChars[i] = temp;
}
return adjs;
}
private List<List<String>> dfs(String src, String dest,
Map<String,List<String>> adjacency,
Map<String,List<List<String>>> memo) {
if( memo.containsKey(src) )
return memo.get(src);
List<List<String>> paths = new ArrayList();
// reached dest? return list with dest word
if( src.equals( dest ) ) {
paths.add( new ArrayList(){{ add(dest); }} );
return paths;
}
// no adjacent for curr word? return empty list
List<String> adjacents = adjacency.get(src);
if( adjacents == null || adjacents.isEmpty() )
return paths;
for(String adj : adjacents) {
List<List<String>> adjPaths = dfs(adj, dest, adjacency, memo);
for(List<String> path : adjPaths) {
if( path.isEmpty() ) continue;
List<String> newPath = new ArrayList(){{ add(src); }};
newPath.addAll(path);
paths.add(newPath);
}
}
memo.put(src, paths);
return paths;
}
}