|
| 1 | +/** |
| 2 | + * @param {character[][]} board |
| 3 | + * @param {string[]} words |
| 4 | + * @return {string[]} |
| 5 | + */ |
| 6 | +class Trie { |
| 7 | + constructor() { |
| 8 | + this.word = null |
| 9 | + this.children = new Map() |
| 10 | + } |
| 11 | + add(word) { |
| 12 | + let cur = this |
| 13 | + for (let i = 0; i < word.length; i++) { |
| 14 | + if (!cur.children.has(word[i])) { |
| 15 | + cur.children.set(word[i], new Trie()) |
| 16 | + } |
| 17 | + cur = cur.children.get(word[i]) |
| 18 | + } |
| 19 | + cur.word = word |
| 20 | + } |
| 21 | + addArr(words) { |
| 22 | + words.forEach(word => this.add(word)) |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +const findWords = function(board, words) { |
| 27 | + const trie = new Trie() |
| 28 | + trie.addArr(words) |
| 29 | + const results = [] |
| 30 | + const dirs = [[-1, 0], [1, 0], [0, 1], [0, -1]] |
| 31 | + for (let i = 0; i < board.length; i++) { |
| 32 | + for (let j = 0; j < board[0].length; j++) { |
| 33 | + dfs(board, i, j, trie, results, dirs) |
| 34 | + } |
| 35 | + } |
| 36 | + return results |
| 37 | +} |
| 38 | + |
| 39 | +const dfs = (board, i, j, trie, results, dirs) => { |
| 40 | + if(i < 0 || j < 0 || i >= board.length || j >= board[0].length) return |
| 41 | + const char = board[i][j] |
| 42 | + if (!trie.children.has(char)) return |
| 43 | + |
| 44 | + const nextTrie = trie.children.get(char) |
| 45 | + if (nextTrie.word) { |
| 46 | + results.push(nextTrie.word) |
| 47 | + nextTrie.word = null |
| 48 | + } |
| 49 | + |
| 50 | + for(let dir of dirs) { |
| 51 | + board[i][j] = '#' |
| 52 | + dfs(board, i + dir[0], j + dir[1], nextTrie, results, dirs) |
| 53 | + board[i][j] = char |
| 54 | + } |
| 55 | + |
| 56 | +} |
0 commit comments