|
| 1 | +function exist(board: string[][], word: string): boolean { |
| 2 | + const m = board.length; |
| 3 | + const n = board[0].length; |
| 4 | + |
| 5 | + const visited: boolean[][] = Array.from({ length: m }, () => Array(n).fill(false)); |
| 6 | + |
| 7 | + const isValidCoordinates = (index: number, x: number, y: number): boolean => { |
| 8 | + if (x >= 0 && x < m && y >= 0 && y < n && word[index] === board[x][y] && !visited[x][y]) return true; |
| 9 | + return false; |
| 10 | + }; |
| 11 | + |
| 12 | + const backtrack = (index: number, cx: number, cy: number): boolean => { |
| 13 | + if (index === word.length - 1 && board[cx][cy] === word[index]) return true; |
| 14 | + |
| 15 | + if (board[cx][cy] !== word[index]) return false; |
| 16 | + |
| 17 | + for (const [dx, dy] of [ |
| 18 | + [0, 1], |
| 19 | + [0, -1], |
| 20 | + [1, 0], |
| 21 | + [-1, 0], |
| 22 | + ]) { |
| 23 | + const [nx, ny] = [cx + dx, cy + dy]; |
| 24 | + |
| 25 | + if (isValidCoordinates(index + 1, nx, ny)) { |
| 26 | + visited[nx][ny] = true; |
| 27 | + const result = backtrack(index + 1, nx, ny); |
| 28 | + if (result) return true; |
| 29 | + visited[nx][ny] = false; |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + return false; |
| 34 | + }; |
| 35 | + |
| 36 | + for (let i = 0; i < m; i++) { |
| 37 | + for (let j = 0; j < n; j++) { |
| 38 | + if (board[i][j] === word[0]) { |
| 39 | + visited[i][j] = true; |
| 40 | + const result: boolean = backtrack(0, i, j); |
| 41 | + if (result) return true; |
| 42 | + visited[i][j] = false; |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + return false; |
| 48 | +} |
0 commit comments