|
| 1 | +/** |
| 2 | + * @param {string} beginWord |
| 3 | + * @param {string} endWord |
| 4 | + * @param {string[]} wordList |
| 5 | + * @return {string[][]} |
| 6 | + */ |
| 7 | +const findLadders = function (beginWord, endWord, wordList) { |
| 8 | + const res = [] |
| 9 | + if (!wordList.includes(endWord)) return res |
| 10 | + const set1 = new Set([beginWord]), |
| 11 | + set2 = new Set([endWord]), |
| 12 | + wordSet = new Set(wordList), |
| 13 | + temp = [beginWord] |
| 14 | + const map = new Map() |
| 15 | + const traverse = (set1, set2, dir) => { |
| 16 | + if (set1.size === 0) return false |
| 17 | + if (set1.size > set2.size) return traverse(set2, set1, !dir) |
| 18 | + for (const val of set1.values()) { |
| 19 | + if (wordSet.has(val)) wordSet.delete(val) |
| 20 | + } |
| 21 | + for (const val of set2.values()) { |
| 22 | + if (wordSet.has(val)) wordSet.delete(val) |
| 23 | + } |
| 24 | + const set = new Set() |
| 25 | + let done = false |
| 26 | + for (const str of set1.values()) { |
| 27 | + for (let i = 0; i < str.length; i++) { |
| 28 | + for (let ch = 'a'.charCodeAt(); ch <= 'z'.charCodeAt(); ch++) { |
| 29 | + const word = |
| 30 | + str.slice(0, i) + String.fromCharCode(ch) + str.slice(i + 1) |
| 31 | + const key = dir ? str : word |
| 32 | + const val = dir ? word : str |
| 33 | + const list = map.get(key) || [] |
| 34 | + if (set2.has(word)) { |
| 35 | + done = true |
| 36 | + list.push(val) |
| 37 | + map.set(key, list) |
| 38 | + } |
| 39 | + if (!done && wordSet.has(word)) { |
| 40 | + set.add(word) |
| 41 | + list.push(val) |
| 42 | + map.set(key, list) |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + return done || traverse(set2, set, !dir) |
| 48 | + } |
| 49 | + const dfs = (word) => { |
| 50 | + if (word === endWord) { |
| 51 | + res.push(temp.slice()) |
| 52 | + return |
| 53 | + } |
| 54 | + const nei = map.get(word) || [] |
| 55 | + for (const w of nei) { |
| 56 | + temp.push(w) |
| 57 | + dfs(w) |
| 58 | + temp.pop() |
| 59 | + } |
| 60 | + } |
| 61 | + traverse(set1, set2, true) |
| 62 | + dfs(beginWord) |
| 63 | + return res |
| 64 | +} |
0 commit comments