|
| 1 | +/** |
| 2 | + * board ์์ ์ฃผ์ด์ง ๋จ์ด๋ฅผ ์ฐพ์ ์ ์๋์ง ์ฌ๋ถ ํ์ธ (boolean) |
| 3 | + * @param {string[][]} board - ๋จ์ด๋ฅผ ํ์ํ 2D board |
| 4 | + * @param {string} word - ์ฐพ๊ณ ์ ํ๋ ๋จ์ด |
| 5 | + * @returns {boolean} - ๋จ์ด๊ฐ ๊ฒฉ์์์ ์กด์ฌํ๋ฉด true, ๊ทธ๋ ์ง ์์ผ๋ฉด false |
| 6 | + * |
| 7 | + * ์๊ฐ ๋ณต์ก๋: O(N * M * 4^L) |
| 8 | + * - N: board์ ํ ๊ฐ์ |
| 9 | + * - M: board์ ์ด ๊ฐ์ |
| 10 | + * - L: word์ ๊ธธ์ด |
| 11 | + * |
| 12 | + * ๊ณต๊ฐ ๋ณต์ก๋: O(L) (์ฌ๊ท ํธ์ถ ์คํ) |
| 13 | + */ |
| 14 | +function exist(board: string[][], word: string): boolean { |
| 15 | + const rows = board.length; |
| 16 | + const cols = board[0].length; |
| 17 | + |
| 18 | + // ๋ฐฉํฅ ๋ฐฐ์ด (์, ํ, ์ข, ์ฐ) |
| 19 | + const directions = [ |
| 20 | + [0, -1], // ์ |
| 21 | + [0, 1], // ํ |
| 22 | + [-1, 0], // ์ข |
| 23 | + [1, 0], // ์ฐ |
| 24 | + ]; |
| 25 | + |
| 26 | + /** |
| 27 | + * DFS ํ์(๊น์ด ์ฐ์ ํ์)์ ํตํด ๋จ์ด๋ฅผ ์ฐพ๋ ํจ์ |
| 28 | + * @param {number} x - ํ์ฌ x ์ขํ (์ด) |
| 29 | + * @param {number} y - ํ์ฌ y ์ขํ (ํ) |
| 30 | + * @param {number} index - ํ์ฌ ํ์ ์ค์ธ word์ ๋ฌธ์ ์ธ๋ฑ์ค |
| 31 | + * @returns {boolean} - ํ์ฌ ๊ฒฝ๋ก๊ฐ ์ ํจํ๋ฉด true, ์ ํจํ์ง ์์ผ๋ฉด false |
| 32 | + */ |
| 33 | + const dfs = (x: number, y: number, index: number): boolean => { |
| 34 | + // ๋จ์ด๋ฅผ ๋ชจ๋ ์ฐพ์์ ๊ฒฝ์ฐ |
| 35 | + if (index === word.length) return true; |
| 36 | + |
| 37 | + // ๋ฒ์๋ฅผ ๋ฒ์ด๋๊ฑฐ๋ ๋ฌธ์๊ฐ ์ผ์นํ์ง ์๋ ๊ฒฝ์ฐ |
| 38 | + if (x < 0 || y < 0 || x >= cols || y >= rows || board[y][x] !== word[index]) { |
| 39 | + return false; |
| 40 | + } |
| 41 | + |
| 42 | + // ํ์ฌ ์์น ๋ฐฉ๋ฌธ ์ฒ๋ฆฌ (์์ ์์ ) |
| 43 | + const temp = board[y][x]; |
| 44 | + board[y][x] = "#"; |
| 45 | + |
| 46 | + // ์ํ์ข์ฐ ํ์ |
| 47 | + for (const [dx, dy] of directions) { |
| 48 | + if (dfs(x + dx, y + dy, index + 1)) { |
| 49 | + return true; |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + // ๋ฐฑํธ๋ํน: ์
๊ฐ ๋ณต๊ตฌ |
| 54 | + board[y][x] = temp; |
| 55 | + |
| 56 | + return false; |
| 57 | + }; |
| 58 | + |
| 59 | + // board์์ word ์ฒซ๊ธ์๊ฐ ์ผ์นํ๋ ๊ฒฝ์ฐ ํ์ ์์ |
| 60 | + for (let y = 0; y < rows; y++) { |
| 61 | + for (let x = 0; x < cols; x++) { |
| 62 | + if (board[y][x] === word[0] && dfs(x, y, 0)) { |
| 63 | + return true; |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + return false; |
| 69 | +} |
| 70 | + |
0 commit comments