|
| 1 | +class TrieNode { |
| 2 | + constructor() { |
| 3 | + this.children = {}; |
| 4 | + this.isWord = false; |
| 5 | + } |
| 6 | + |
| 7 | + add(word) { |
| 8 | + let node = this; |
| 9 | + for (let ch of word) { |
| 10 | + if (!node.children[ch]) { |
| 11 | + node.children[ch] = new TrieNode(); |
| 12 | + } |
| 13 | + node = node.children[ch]; |
| 14 | + } |
| 15 | + node.isWord = true; |
| 16 | + } |
| 17 | +} |
| 18 | + |
| 19 | +/** |
| 20 | + * @param {character[][]} board |
| 21 | + * @param {string[]} words |
| 22 | + * @return {string[]} |
| 23 | + */ |
| 24 | +var findWords = function(board, words) { |
| 25 | + const root = new TrieNode(); |
| 26 | + for (let word of words) { |
| 27 | + root.add(word); |
| 28 | + } |
| 29 | + |
| 30 | + const ROWS = board.length; |
| 31 | + const COLS = board[0].length; |
| 32 | + const res = new Set(); |
| 33 | + const visit = new Set(); |
| 34 | + |
| 35 | + const dfs = (r, c, node, word) => { |
| 36 | + if ( |
| 37 | + r < 0 || c < 0 || |
| 38 | + r >= ROWS || c >= COLS || |
| 39 | + visit.has(`${r},${c}`) || |
| 40 | + !node.children[board[r][c]] |
| 41 | + ) return; |
| 42 | + |
| 43 | + visit.add(`${r},${c}`); |
| 44 | + node = node.children[board[r][c]]; |
| 45 | + word += board[r][c]; |
| 46 | + |
| 47 | + if (node.isWord) { |
| 48 | + res.add(word); |
| 49 | + } |
| 50 | + |
| 51 | + dfs(r + 1, c, node, word); |
| 52 | + dfs(r - 1, c, node, word); |
| 53 | + dfs(r, c + 1, node, word); |
| 54 | + dfs(r, c - 1, node, word); |
| 55 | + |
| 56 | + visit.delete(`${r},${c}`); |
| 57 | + }; |
| 58 | + |
| 59 | + for (let r = 0; r < ROWS; r++) { |
| 60 | + for (let c = 0; c < COLS; c++) { |
| 61 | + dfs(r, c, root, ""); |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + return Array.from(res); |
| 66 | +}; |
| 67 | + |
0 commit comments