forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0127-word-ladder.java
57 lines (53 loc) · 1.77 KB
/
0127-word-ladder.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
package java;
class Solution {
public int ladderLength(
String beginWord,
String endWord,
List<String> wordList
) {
Map<String, List<String>> adjlist = new HashMap<>();
wordList.add(beginWord);
for (String word : wordList) {
StringBuilder string = null;
for (int i = 0; i < word.length(); i++) {
string = new StringBuilder(word);
string.setCharAt(i, '*');
List<String> wordlist = adjlist.getOrDefault(
string.toString(),
new ArrayList<String>()
);
wordlist.add(word);
adjlist.put(string.toString(), wordlist);
}
}
Queue<String> queue = new LinkedList<>();
queue.offer(beginWord);
Set<String> visited = new HashSet<>();
visited.add(beginWord);
int step = 1;
StringBuilder string = null;
while (!queue.isEmpty()) {
step++;
int size = queue.size();
for (int j = 0; j < size; j++) {
String str = queue.poll();
for (int i = 0; i < str.length(); i++) {
string = new StringBuilder(str);
string.setCharAt(i, '*');
for (String pat : adjlist.get(string.toString())) {
if (pat.equals(endWord)) {
return step;
}
if (visited.contains(pat)) {
continue;
}
queue.offer(pat);
visited.add(pat);
}
}
}
// step++;
}
return 0;
}
}