-
Notifications
You must be signed in to change notification settings - Fork 16
/
WordLadder.java
58 lines (50 loc) · 1.75 KB
/
WordLadder.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
// https://leetcode.com/problems/word-ladder
// T: O(nB + n^m * nm)
// S: O(nB + n^m)
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Set;
public class WordLadder {
private record Info(String string, int steps) {}
// n = possible chars, m = |s|
// V = n^m
// BFS, T: O(V + E) = O(nB + n^m * nm), S: O(n^m)
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
final Set<String> words = new HashSet<>(wordList);
if (!words.contains(endWord)) {
return 0;
}
final Queue<Info> queue = new LinkedList<>() {{ add(new Info(beginWord, 0)); }};
final Set<String> visited = new HashSet<>();
while (!queue.isEmpty()) {
final Info info = queue.poll();
if (visited.contains(info.string)) {
continue;
}
visited.add(info.string);
if (endWord.equals(info.string)) {
return info.steps + 1;
}
for (String neighbour : validMutations(words, info.string)) {
queue.add(new Info(neighbour, info.steps + 1));
}
}
return -1;
}
// T: O(n * m), S: O(n * m)
private static List<String> validMutations(Set<String> words, String string) {
final List<String> list = new ArrayList<>();
for (int i = 0 ; i < string.length() ; i++) {
for (char c = 'a' ; c <= 'z' ; c++) {
final String word = string.substring(0, i) + c + string.substring(i + 1);
if (words.contains(word)) {
list.add(word);
}
}
}
return list;
}
}