forked from algorithm022/algorithm022
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLadderLength2.java
More file actions
97 lines (88 loc) · 2.92 KB
/
Copy pathLadderLength2.java
File metadata and controls
97 lines (88 loc) · 2.92 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package practice.graph;
import java.util.*;
public class LadderLength2 {
private static final int INF = 1 << 20;
private Map<String, Integer> wordId;
private ArrayList<String> idWord;
private ArrayList<Integer>[] edges;
public LadderLength2() {
wordId = new HashMap<>();
idWord = new ArrayList<>();
}
/**
* 广度优先搜索
* @param beginWord
* @param endWord
* @param wordList
* @return
*/
public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {
int id = 0;
for (String word : wordList) {
if (!wordId.containsKey(word)) {
wordId.put(word, id++);
idWord.add(word);
}
}
if (!wordId.containsKey(endWord)) {
return new ArrayList<>();
}
if (!wordId.containsKey(beginWord)) {
wordId.put(beginWord, id++);
idWord.add(beginWord);
}
edges = new ArrayList[idWord.size()];
for (int i = 0; i < idWord.size(); i++) {
edges[i] = new ArrayList<>();
}
for (int i = 0; i < idWord.size(); i++) {
for (int j = i + 1; j < idWord.size(); j++) {
if (transformCheck(idWord.get(i), idWord.get(j))) {
edges[i].add(j);
edges[j].add(i);
}
}
}
int dest = wordId.get(endWord);
List<List<String>> res = new ArrayList<>(); // 存答案
int[] cost = new int[id];
for (int i = 0; i < id; i++) {
cost[i] = INF;
}
Queue<ArrayList<Integer>> q = new LinkedList<>();
ArrayList<Integer> tmpBegin = new ArrayList<>();
tmpBegin.add(wordId.get(beginWord));
q.add(tmpBegin);
cost[wordId.get(beginWord)] = 0;
while (!q.isEmpty()) {
ArrayList<Integer> now = q.poll();
int last = now.get(now.size() - 1);
if (last == dest) {
ArrayList<String> tmp = new ArrayList<>();
for (int index : now) {
tmp.add(idWord.get(index));
}
res.add(tmp);
} else {
for (int i = 0; i < edges[last].size(); i++) {
int to = edges[last].get(i);
if (cost[last] + 1 <= cost[to]) {
cost[to] = cost[last] + 1;
ArrayList<Integer> tmp = new ArrayList<>(now); tmp.add(to);
q.add(tmp);
}
}
}
}
return res;
}
boolean transformCheck(String str1, String str2) {
int differences = 0;
for (int i = 0; i < str1.length() && differences < 2; i++) {
if (str1.charAt(i) != str2.charAt(i)) {
++differences;
}
}
return differences == 1;
}
}