-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path127.word-ladder.java
More file actions
45 lines (39 loc) · 1.33 KB
/
127.word-ladder.java
File metadata and controls
45 lines (39 loc) · 1.33 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
/*
* @lc app=leetcode id=127 lang=java
*
* [127] Word Ladder
*/
// @lc code=start
class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
Set<String> wordSet = new HashSet<>(wordList);
Set<String> visited = new HashSet<>();
Queue<String> queue = new LinkedList<>();
queue.add(beginWord);
visited.add(beginWord);
int level = 0;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
String currWord = queue.poll();
if (currWord.equals(endWord)) return level + 1;
char[] wordArr = currWord.toCharArray();
for (int j = 0; j < wordArr.length; j++) {
char temp = wordArr[j];
for (char c = 'a'; c <= 'z'; c++) {
wordArr[j] = c;
String newWord = new String(wordArr);
if (!visited.contains(newWord) && wordSet.contains(newWord)) {
queue.add(newWord);
visited.add(newWord);
}
}
wordArr[j] = temp;
}
}
level++;
}
return 0;
}
}
// @lc code=end