|
| 1 | +// k: length of word, h: height of board, w: width of board |
| 2 | +// Time complexity: O(4^k * h * w) |
| 3 | +// Space complexity: O(4^k) |
| 4 | + |
| 5 | +class Node { |
| 6 | + constructor(value = "") { |
| 7 | + this.value = value; |
| 8 | + this.children = new Map(); |
| 9 | + this.isEnd = false; |
| 10 | + } |
| 11 | +} |
| 12 | +class Trie { |
| 13 | + constructor() { |
| 14 | + this.head = new Node(); |
| 15 | + } |
| 16 | + |
| 17 | + add(str) { |
| 18 | + let current = this.head; |
| 19 | + |
| 20 | + for (const chr of str) { |
| 21 | + if (!current.children.has(chr)) { |
| 22 | + current.children.set(chr, new Node(current.value + chr)); |
| 23 | + } |
| 24 | + |
| 25 | + current = current.children.get(chr); |
| 26 | + } |
| 27 | + |
| 28 | + current.isEnd = true; |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +/** |
| 33 | + * @param {character[][]} board |
| 34 | + * @param {string[]} words |
| 35 | + * @return {string[]} |
| 36 | + */ |
| 37 | +var findWords = function (board, words) { |
| 38 | + const answer = new Set(); |
| 39 | + |
| 40 | + const h = board.length; |
| 41 | + const w = board[0].length; |
| 42 | + |
| 43 | + const dy = [1, 0, -1, 0]; |
| 44 | + const dx = [0, 1, 0, -1]; |
| 45 | + const checked = Array.from({ length: h }, () => |
| 46 | + Array.from({ length: w }, () => false) |
| 47 | + ); |
| 48 | + |
| 49 | + const dfs = (current, children) => { |
| 50 | + const [cy, cx] = current; |
| 51 | + |
| 52 | + if (!children.has(board[cy][cx])) { |
| 53 | + return; |
| 54 | + } |
| 55 | + |
| 56 | + if (children.get(board[cy][cx]).isEnd) { |
| 57 | + answer.add(children.get(board[cy][cx]).value); |
| 58 | + } |
| 59 | + |
| 60 | + for (let j = 0; j < dx.length; j++) { |
| 61 | + const nx = cx + dx[j]; |
| 62 | + const ny = cy + dy[j]; |
| 63 | + |
| 64 | + if (nx >= 0 && nx < w && ny >= 0 && ny < h && !checked[ny][nx]) { |
| 65 | + checked[ny][nx] = true; |
| 66 | + dfs([ny, nx], children.get(board[cy][cx]).children); |
| 67 | + checked[ny][nx] = false; |
| 68 | + } |
| 69 | + } |
| 70 | + }; |
| 71 | + |
| 72 | + const trie = new Trie(); |
| 73 | + |
| 74 | + for (const word of words) { |
| 75 | + trie.add(word); |
| 76 | + } |
| 77 | + |
| 78 | + for (let i = 0; i < h; i++) { |
| 79 | + for (let j = 0; j < w; j++) { |
| 80 | + checked[i][j] = true; |
| 81 | + dfs([i, j], trie.head.children); |
| 82 | + checked[i][j] = false; |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + return [...answer]; |
| 87 | +}; |
0 commit comments