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