-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0127-word-ladder.ts
45 lines (42 loc) · 1.23 KB
/
0127-word-ladder.ts
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
function ladderLength(
beginWord: string,
endWord: string,
wordList: string[]
): number {
if (!wordList.includes(endWord)) {
return 0;
}
let patternMap = {};
wordList.push(beginWord);
for (let word of wordList) {
for (let x = 0; x < word.length; x++) {
const pattern = word.slice(0, x) + '*' + word.slice(x + 1);
patternMap[pattern] = patternMap[pattern] || [];
patternMap[pattern].push(word);
}
}
let wordCount = 1,
queue = [beginWord],
visited = [beginWord];
while (queue.length) {
const levelSize = queue.length;
for (let x = 0; x < levelSize; x++) {
const word = queue.shift();
if (word === endWord) {
return wordCount;
}
for (let x = 0; x < word.length; x++) {
const pattern = word.slice(0, x) + '*' + word.slice(x + 1);
for (let nei of patternMap[pattern]) {
if (nei in visited) {
continue;
}
visited[nei] = nei;
queue.push(nei);
}
}
}
wordCount++;
}
return 0;
}