forked from algorithm009-class01/algorithm009-class01
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLadderLength.java
More file actions
71 lines (64 loc) · 2.72 KB
/
LadderLength.java
File metadata and controls
71 lines (64 loc) · 2.72 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
package serach;
import java.util.*;
public class LadderLength {
public int ladderLength(String beginWord, String endWord, List<String> wordList){
//先将wordList放到哈希表里面,便于判断某个单词是否再wordList里面
Set<String> wordSet = new HashSet<>(wordList);
if (wordSet.size() == 0 || !wordSet.contains(endWord)){
return 0;
}
wordSet.remove(beginWord);
//图的广度优先遍历,必须使用的队列和表示是否访问过的visited(数组,哈希表)
Queue<String> queue = new LinkedList<>();
queue.offer(beginWord);
Set<String> visited = new HashSet<>();
visited.add(beginWord);
int wordLen = beginWord.length();
//包含起点,因此初始化的时候步数为1
int step = 1;
while (!queue.isEmpty()){
int currentSize = queue.size();
for (int i = 0; i < currentSize; i++) {
//依次遍历当前队列中的词
String word = queue.poll();
char[] charArray = word.toCharArray();
//修改每一个字符
for (int j = 0; j < wordLen; j++) {
//一轮以后应该重置,否则结果不正确
char originChar = charArray[j];
for (char k = 'a';k <= 'z';k++){
if (k == originChar){
continue;
}
charArray[j] = k;
String nextWord = String.valueOf(charArray);
if(wordSet.contains(nextWord)){
if (nextWord.equals(endWord)){
return step + 1;
}
if (!visited.contains(nextWord)){
queue.add(nextWord);
//注意:添加到队列之后,必须马上标记为已经访问
visited.add(nextWord);
}
}
}
//恢复
charArray[j] = originChar;
}
}
step++;
}
return 0;
}
public static void main(String[] args) {
String beginWord = "hit";
String endWord = "cog";
List<String> wordList = new ArrayList<>();
String[] wordListArray = new String[]{"hot", "dot", "dog", "lot", "log", "cog"};
Collections.addAll(wordList, wordListArray);
LadderLength solution = new LadderLength();
int res = solution.ladderLength(beginWord, endWord, wordList);
System.out.println(res);
}
}