1
const isMatch = (currWord, nextWord) => {3
for (let i = 0; i < nextWord.length; i += 1) {4
if (nextWord[i] !== currWord[i]) {12
const getNextWords = (lastRung, dictionary) => {14
for (const word of dictionary) {15
if (isMatch(word, lastRung)) {23
const updateLadders = (ladders, dictionary) => {24
const updatedLadders = [];25
const nextRung = new Set();27
for (const ladder of ladders) {28
const nextWords = getNextWords(ladder[ladder.length - 1], dictionary);29
for (const nextWord of nextWords) {30
updatedLadders.push([...ladder, nextWord]);31
nextRung.add(nextWord);35
return [updatedLadders, nextRung];38
const updateDictionary = (dictionary, nextRung) => {39
return dictionary.filter((word) => !nextRung.has(word));42
// BFS traversal from endWord to beginWord43
// This limits the paths that we'll need to consider during our traversal from beingWord to endWord44
const getDictionary = (wordList, endWord, beginWord) => {45
const dictionary = new Set();47
let currRung = [endWord];48
while (currRung.length > 0) {49
const nextRung = new Set();50
if (!wordList.includes(beginWord)) break;52
while (currRung.length > 0) {53
const currWord = currRung.pop();54
dictionary.add(currWord);56
for (const nextWord of wordList) {57
if (isMatch(currWord, nextWord)) {58
nextRung.add(nextWord);63
currRung = [...nextRung];64
wordList = wordList.filter((word) => !nextRung.has(word));67
return [...dictionary];70
var findLadders = function (beginWord, endWord, wordList) {71
if (!wordList.includes(endWord)) return [];72
if (!wordList.includes(beginWord)) wordList.push(beginWord);75
const saveResult = (ladders) => {76
for (const ladder of ladders) {77
if (ladder[ladder.length - 1] === endWord) {83
let ladders = [[beginWord]];84
let dictionary = getDictionary(wordList, endWord, beginWord);85
while (ladders.length > 0) {86
if (!dictionary.includes(endWord)) {91
const [updatedLadders, nextRung] = updateLadders(ladders, dictionary);92
ladders = updatedLadders;93
dictionary = updateDictionary(dictionary, nextRung);