|
| 1 | +/** |
| 2 | + * https://leetcode.com/problems/word-search |
| 3 | + * time complexity : O(m * n * 4^L) |
| 4 | + * space complexity : O(L) |
| 5 | + */ |
| 6 | +const dfs = (r: number, c: number, index: number, board: string[][], word: string, rows: number, cols: number): boolean => { |
| 7 | + if (index === word.length) return true; |
| 8 | + |
| 9 | + if (r < 0 || r >= rows || c < 0 || c >= cols || board[r][c] !== word[index]) return false; |
| 10 | + const temp = board[r][c]; |
| 11 | + |
| 12 | + board[r][c] = '🚪'; |
| 13 | + const found = dfs(r + 1, c, index + 1, board, word, rows, cols) || |
| 14 | + dfs(r - 1, c, index + 1, board, word, rows, cols) || |
| 15 | + dfs(r, c + 1, index + 1, board, word, rows, cols) || |
| 16 | + dfs(r, c - 1, index + 1, board, word, rows, cols); |
| 17 | + |
| 18 | + board[r][c] = temp; |
| 19 | + |
| 20 | + return found; |
| 21 | +}; |
| 22 | + |
| 23 | +function exist(board: string[][], word: string): boolean { |
| 24 | + const rows = board.length; |
| 25 | + const cols = board[0].length; |
| 26 | + |
| 27 | + for (let r = 0; r < rows; r++) { |
| 28 | + for (let c = 0; c < cols; c++) { |
| 29 | + if (dfs(r, c, 0, board, word, rows, cols)) return true; |
| 30 | + } |
| 31 | + } |
| 32 | + return false; |
| 33 | +} |
0 commit comments