forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0127-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
functionladderLength(
beginWord: string,
endWord: string,
wordList: string[]
): number{
if(!wordList.includes(endWord)){
return0;
}
letpatternMap={};
wordList.push(beginWord);
for(letwordofwordList){
for(letx=0;x<word.length;x++){
constpattern=word.slice(0,x)+'*'+word.slice(x+1);
patternMap[pattern]=patternMap[pattern]||[];
patternMap[pattern].push(word);
}
}
letwordCount=1,
queue=[beginWord],
visited=[beginWord];
while(queue.length){
constlevelSize=queue.length;
for(letx=0;x<levelSize;x++){
constword=queue.shift();
if(word===endWord){
returnwordCount;
}
for(letx=0;x<word.length;x++){
constpattern=word.slice(0,x)+'*'+word.slice(x+1);
for(letneiofpatternMap[pattern]){
if(neiinvisited){
continue;
}
visited[nei]=nei;
queue.push(nei);
}
}
}
wordCount++;
}
return0;
}