|
| 1 | +/** |
| 2 | + * 126. Word Ladder II |
| 3 | + * https://leetcode.com/problems/word-ladder-ii/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * A transformation sequence from word beginWord to word endWord using a dictionary wordList |
| 7 | + * is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: |
| 8 | + * - Every adjacent pair of words differs by a single letter. |
| 9 | + * - Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList. |
| 10 | + * - sk == endWord |
| 11 | + * |
| 12 | + * Given two words, beginWord and endWord, and a dictionary wordList, return all the shortest |
| 13 | + * transformation sequences from beginWord to endWord, or an empty list if no such sequence |
| 14 | + * exists. Each sequence should be returned as a list of the words [beginWord, s1, s2, ..., sk]. |
| 15 | + */ |
| 16 | + |
| 17 | +/** |
| 18 | + * @param {string} beginWord |
| 19 | + * @param {string} endWord |
| 20 | + * @param {string[]} wordList |
| 21 | + * @return {string[][]} |
| 22 | + */ |
| 23 | +var findLadders = function(beginWord, endWord, wordList) { |
| 24 | + const set = new Set(wordList); |
| 25 | + const queue = [beginWord]; |
| 26 | + const group = []; |
| 27 | + let isEnd = false; |
| 28 | + |
| 29 | + while (queue.length && !isEnd) { |
| 30 | + group.push([...queue]); |
| 31 | + const limit = queue.length; |
| 32 | + for (let i = 0; i < limit && !isEnd; i++) { |
| 33 | + const from = queue.shift(); |
| 34 | + for (const word of set) { |
| 35 | + if (!isValid(from, word)) { |
| 36 | + continue; |
| 37 | + } else if (word === endWord) { |
| 38 | + isEnd = true; |
| 39 | + break; |
| 40 | + } |
| 41 | + queue.push(word); |
| 42 | + set.delete(word); |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + if (!isEnd) { |
| 48 | + return []; |
| 49 | + } |
| 50 | + |
| 51 | + const result = [[endWord]]; |
| 52 | + for (let i = group.length - 1; i >= 0; i--) { |
| 53 | + const limit = result.length; |
| 54 | + for (let j = 0; j < limit; j++) { |
| 55 | + const path = result.shift(); |
| 56 | + for (const word of group[i]) { |
| 57 | + if (!isValid(path[0], word)) { |
| 58 | + continue; |
| 59 | + } |
| 60 | + result.push([word, ...path]); |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + return result; |
| 66 | + |
| 67 | + function isValid(a, b) { |
| 68 | + let count = 0; |
| 69 | + for (let i = 0; i < a.length && count < 2; i++) { |
| 70 | + if (a[i] !== b[i]) { |
| 71 | + count++; |
| 72 | + } |
| 73 | + } |
| 74 | + return count === 1; |
| 75 | + } |
| 76 | +}; |
0 commit comments