-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
63 lines (50 loc) · 1.71 KB
/
Solution.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
import java.util.*;
class Solution {
// beginWord.length() = M, wordLise.size() = N
// M * M * N = O(M^2 * N)
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
if (wordList.isEmpty()) {
return beginWord.equals(endWord) ? 1 : 0;
}
Queue<String> queue = new LinkedList<>();
Set<String> words = new HashSet<>(wordList);
queue.offer(beginWord);
int level = 1;
while (!queue.isEmpty()) {
int N = queue.size();
for (int i = 0; i < N; ++i) {
String curWord = queue.poll();
// Find next word
char[] curWordChars = curWord.toCharArray();
for (int j = 0; j < curWordChars.length; ++j) {
for (char k = 'a'; k <= 'z'; ++k) {
char tmp = curWordChars[j];
curWordChars[j] = k;
String nextWord = new String(curWordChars);
if (words.contains(nextWord)) {
if (nextWord.equals(endWord)) {
return level + 1;
}
queue.offer(nextWord);
words.remove(nextWord);
}
curWordChars[j] = tmp;
}
}
}// for
level++;
}//while
return 0;
}
public static void main(String[] args) {
System.out.println("Thsi is wordladder");
}
}
/*
aot
bot
.
dot ->
.
zot
*/