Skip to content

Commit 1365a5f

Browse files
committed
feat: add js solution to 127 word ladder
1 parent 9d23c3c commit 1365a5f

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

javascript/127-Word-Ladder.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
var ladderLength = function (beginWord, endWord, wordList) {
2+
if (!wordList.includes(endWord)) return 0;
3+
let patternMap = {};
4+
wordList.push(beginWord);
5+
6+
for (let word of wordList) {
7+
for (let x = 0; x < word.length; x++) {
8+
const pattern = word.slice(0, x) + "*" + word.slice(x + 1);
9+
patternMap[pattern] = patternMap[pattern] || [];
10+
patternMap[pattern].push(word);
11+
}
12+
}
13+
14+
let wordCount = 1,
15+
queue = [beginWord],
16+
visited = [beginWord];
17+
while (queue.length) {
18+
const levelSize = queue.length;
19+
for (let x = 0; x < levelSize; x++) {
20+
const word = queue.shift();
21+
if (word === endWord) return wordCount;
22+
for (let x = 0; x < word.length; x++) {
23+
const pattern = word.slice(0, x) + "*" + word.slice(x + 1);
24+
for (let nei of patternMap[pattern]) {
25+
if (nei in visited) continue;
26+
visited[nei] = true;
27+
queue.push(nei);
28+
}
29+
}
30+
}
31+
wordCount += 1;
32+
}
33+
return 0;
34+
};

0 commit comments

Comments
 (0)