1
const buildTrie = (words) => {3
const addToTrie = (word, index = 0, node = trie) => {4
const char = word[index];9
if (index === word.length - 1) {10
node[char].word = word;14
return addToTrie(word, index + 1, node[char]);17
words.map((word) => addToTrie(word));21
const dfs = (i, j, board, node, wordsFound = []) => {22
if (i < 0 || i >= board.length) return wordsFound;23
if (j < 0 || j >= board[board.length - 1].length) return wordsFound;25
const char = board[i][j];26
if (char === "#") return wordsFound;29
if (node[char].word) {30
wordsFound.push(node[char].word);31
node[char].word = null;35
dfs(i + 1, j, board, node[char], wordsFound);36
dfs(i, j + 1, board, node[char], wordsFound);37
dfs(i - 1, j, board, node[char], wordsFound);38
dfs(i, j - 1, board, node[char], wordsFound);45
var findWords = function (board, words) {46
const m = board.length;47
const n = board[m - 1].length;48
const trie = buildTrie(words);51
for (let i = 0; i < m; i += 1) {52
for (let j = 0; j < n; j += 1) {53
result = result.concat(dfs(i, j, board, trie));