-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy path127-Word-Ladder.js
43 lines (35 loc) · 1.12 KB
/
127-Word-Ladder.js
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
/**
* @param {string} beginWord
* @param {string} endWord
* @param {string[]} wordList
* @return {number}
*/
const ladderLength = (beginWord, endWord, wordList) => {
let counter = 1;
let queue = [beginWord];
const words = new Set(wordList);
const visited = new Set(queue);
while (queue.length) {
const next = [];
for (const currentWord of queue) {
if (currentWord === endWord) {
return counter;
}
const currentWordArr = currentWord.split('');
for (let i = 0; i < currentWordArr.length; i++) {
for (let letter = 0; letter < 26; letter++) {
currentWordArr[i] = String.fromCharCode(97 + letter);
const newWord = currentWordArr.join('');
if (!visited.has(newWord) && words.has(newWord)) {
next.push(newWord);
visited.add(newWord);
}
currentWordArr[i] = currentWord[i];
}
}
}
queue = next;
counter++;
}
return 0;
};