-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path127. Word Ladder
53 lines (37 loc) · 1.61 KB
/
127. Word Ladder
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
class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
Set<String> wordSet = new HashSet<>(wordList);
if (!wordSet.contains(endWord)) {
return 0;
}
Queue<String> queue = new LinkedList<>();
queue.add(beginWord);
Set<String> visited = new HashSet<>();
visited.add(beginWord);
int level = 1;
while (!queue.isEmpty()) {
int levelSize = queue.size();
for (int i = 0; i < levelSize; i++) {
String word = queue.poll();
for (int j = 0; j < word.length(); j++) {
char[] wordArray = word.toCharArray();
for (char c = 'a'; c <= 'z'; c++) {
char originalChar = wordArray[j];
if (originalChar == c) continue;
wordArray[j] = c;
String newWord = new String(wordArray);
if (newWord.equals(endWord)) {
return level + 1;
}
if (wordSet.contains(newWord) && !visited.contains(newWord)) {
queue.add(newWord);
visited.add(newWord);
}
}
}
}
level++;
}
return 0;
}
}