-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy path0126-word-ladder-ii.js
76 lines (70 loc) · 1.98 KB
/
0126-word-ladder-ii.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/**
* 126. Word Ladder II
* https://leetcode.com/problems/word-ladder-ii/
* Difficulty: Hard
*
* A transformation sequence from word beginWord to word endWord using a dictionary wordList
* is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that:
* - Every adjacent pair of words differs by a single letter.
* - Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList.
* - sk == endWord
*
* Given two words, beginWord and endWord, and a dictionary wordList, return all the shortest
* transformation sequences from beginWord to endWord, or an empty list if no such sequence
* exists. Each sequence should be returned as a list of the words [beginWord, s1, s2, ..., sk].
*/
/**
* @param {string} beginWord
* @param {string} endWord
* @param {string[]} wordList
* @return {string[][]}
*/
var findLadders = function(beginWord, endWord, wordList) {
const set = new Set(wordList);
const queue = [beginWord];
const group = [];
let isEnd = false;
while (queue.length && !isEnd) {
group.push([...queue]);
const limit = queue.length;
for (let i = 0; i < limit && !isEnd; i++) {
const from = queue.shift();
for (const word of set) {
if (!isValid(from, word)) {
continue;
} else if (word === endWord) {
isEnd = true;
break;
}
queue.push(word);
set.delete(word);
}
}
}
if (!isEnd) {
return [];
}
const result = [[endWord]];
for (let i = group.length - 1; i >= 0; i--) {
const limit = result.length;
for (let j = 0; j < limit; j++) {
const path = result.shift();
for (const word of group[i]) {
if (!isValid(path[0], word)) {
continue;
}
result.push([word, ...path]);
}
}
}
return result;
function isValid(a, b) {
let count = 0;
for (let i = 0; i < a.length && count < 2; i++) {
if (a[i] !== b[i]) {
count++;
}
}
return count === 1;
}
};