-
Notifications
You must be signed in to change notification settings - Fork 70
/
res.js
59 lines (51 loc) · 1.48 KB
/
res.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
* res.js
* @authors Joe Jiang (hijiangtao@gmail.com)
* @date 2017-06-21 23:22:33
*
* 127. Word Ladder
* Problem: https://leetcode.com/problems/word-ladder/
* Discuss: https://discuss.leetcode.com/category/135/word-ladder
*
* * Traditional
* * Two-end BFS
* * Dijkstra's algorithm
*
* @param {string} beginWord
* @param {string} endWord
* @param {string[]} wordList
* @return {number}
*/
let ladderLength = function(beginWord, endWord, wordList) {
wordList.push(endWord);
let toVisit = new Set(),
wordDict = new Set(wordList),
dist = 2;
if (wordList.length === wordDict.size) return 0;
addNextWords(beginWord, wordDict, toVisit);
while (toVisit.size > 0) {
let entriesLen = toVisit.size,
mark = 0;
for (let item of toVisit.values()) {
if (mark++ === entriesLen) break;
toVisit.delete(item);
if (item === endWord) return dist;
addNextWords(item, wordDict, toVisit);
}
dist++;
}
return 0;
};
let addNextWords = function(word, wordDict, toVisit) {
wordDict.delete(word);
let len = word.length;
for (let i=0; i<len; i++) {
for (let j=97; j<123; j++) {
let tmp = word.substring(0, i) + String.fromCharCode(j) + word.substring(i+1, len);
if (wordDict.has(tmp)) {
toVisit.add(tmp);
wordDict.delete(tmp);
}
}
}
};