forked from algorithm008-class02/algorithm008-class02
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLadderLength.java
More file actions
53 lines (41 loc) · 1.69 KB
/
LadderLength.java
File metadata and controls
53 lines (41 loc) · 1.69 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
41
42
43
44
45
46
47
48
49
50
51
52
53
package week4;
import javafx.util.Pair;
import java.util.*;
public class LadderLength {
//官网给大答案有问题
public int ladderLength(String beginWord, String endWord, List<String> worldList) {
int L = worldList.size();
Map<String, List<String>> allComboDict = new HashMap<>();
worldList.forEach(world -> {
for (int i = 0; i < L; i++) {
String newWord = world.substring(0, i) + "*" + world.substring(i + 1, L);
List<String> orDefault = allComboDict.getOrDefault(newWord, new ArrayList<String>());
orDefault.add(world);
allComboDict.put(newWord, orDefault);
}
});
Queue<Pair<String, Integer>> queue = new LinkedList<>();
queue.add(new Pair<>(beginWord, 1));
Map<String, Boolean> visited = new HashMap<>();
visited.put(beginWord, true);
while (!queue.isEmpty()) {
Pair<String, Integer> node = queue.remove();
String world = node.getKey();
Integer levle = node.getValue();
for (int i = 0; i < L; i++) {
String newworld = world.substring(0, i) + "*" + world.substring(i + 1, L);
List<String> orDefault = allComboDict.getOrDefault(newworld, new ArrayList<>());
for (String s : orDefault) {
if (s.equals(endWord)) {
return levle + 1;
}
if (!visited.containsKey(s)) {
visited.put(s, true);
queue.add(new Pair<>(s, levle + 1));
}
}
}
}
return 0;
}
}