-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWordLadder.java
More file actions
40 lines (31 loc) · 1.09 KB
/
WordLadder.java
File metadata and controls
40 lines (31 loc) · 1.09 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
package graph;
import java.util.*;
public class WordLadder {
public static int ladderLength(String beginWord, String endWord, List<String> wordList) {
if (!wordList.contains(endWord)) return 0;
int cnt = 0;
Set<String> dict = new HashSet<>(wordList);
Queue<String> que = new LinkedList<>();
que.add(beginWord);
while (!que.isEmpty()) {
cnt++;
int size = que.size();
while (size-- > 0) {
String word = que.poll();
if (word.equals(endWord)) return cnt;
for (int i = 0; i < word.length(); i++) {
for (char ch = 'a'; ch <= 'z'; ch++) {
char[] arr = word.toCharArray();
arr[i] = ch;
String midWord = new String(arr);
if (dict.contains(midWord)) {
que.add(midWord);
dict.remove(midWord);
}
}
}
}
}
return 0;
}
}