|
| 1 | +/** |
| 2 | + * https://leetcode.com/problems/word-search |
| 3 | + * T.C. O(n * m * 4^l) |
| 4 | + * S.C. O(n * m) |
| 5 | + */ |
| 6 | +function exist(board: string[][], word: string): boolean { |
| 7 | + const countMap = new Map<string, number>(); |
| 8 | + |
| 9 | + for (let i = 0; i < word.length; i++) { |
| 10 | + countMap.set(word[i], (countMap.get(word[i]) || 0) + 1); |
| 11 | + } |
| 12 | + for (let i = 0; i < board.length * board[0].length; i++) { |
| 13 | + countMap.set(board[Math.floor(i / board[0].length)][i % board[0].length], 0); |
| 14 | + } |
| 15 | + |
| 16 | + if (Array.from(countMap.values()).some((v) => v > 0)) return false; |
| 17 | + |
| 18 | + let seen = Array.from({ length: board.length }, () => |
| 19 | + new Array(board[0].length).fill(false) |
| 20 | + ); |
| 21 | + const directives = [ |
| 22 | + [0, 1], |
| 23 | + [0, -1], |
| 24 | + [1, 0], |
| 25 | + [-1, 0], |
| 26 | + ]; |
| 27 | + |
| 28 | + function dfs(h: number, w: number, index: number): boolean { |
| 29 | + if (w < 0 || w >= board[0].length) return false; |
| 30 | + if (h < 0 || h >= board.length) return false; |
| 31 | + |
| 32 | + if (seen[h][w]) return false; |
| 33 | + if (board[h][w] !== word[index]) return false; |
| 34 | + if (index === word.length - 1) return true; |
| 35 | + |
| 36 | + seen[h][w] = true; |
| 37 | + |
| 38 | + for (let i = 0; i < 4; i++) { |
| 39 | + const [dh, dw] = directives[i]; |
| 40 | + if (dfs(h + dh, w + dw, index + 1)) { |
| 41 | + return true; |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + seen[h][w] = false; |
| 46 | + return false; |
| 47 | + } |
| 48 | + |
| 49 | + for (let i = 0; i < board.length; i++) { |
| 50 | + for (let j = 0; j < board[0].length; j++) { |
| 51 | + if (dfs(i, j, 0)) { |
| 52 | + return true; |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + return false; |
| 57 | +} |
0 commit comments