|
| 1 | +/** |
| 2 | + * @param {character[][]} board |
| 3 | + * @param {string} word |
| 4 | + * @return {boolean} |
| 5 | + */ |
| 6 | +// DFS ์ฌ์ฉ ์ด์ : ํ ๊ฒฝ๋ก๋ฅผ ๋๊น์ง ํ์ํด์ผ ํ๊ณ , ๊ฒฝ๋ก๋ณ๋ก ๋
๋ฆฝ์ ์ธ ๋ฐฉ๋ฌธ ์ํ๊ฐ ํ์ํ๊ธฐ ๋๋ฌธ |
| 7 | +// BFS ๋ถ๊ฐ ์ด์ : ์ฌ๋ฌ ๊ฒฝ๋ก๋ฅผ ๋์์ ํ์ํ๋ฉด์ ๋ฐฉ๋ฌธ ์ํ๊ฐ ์์ฌ ์ฌ๋ฐ๋ฅธ ๊ฒฝ๋ก๋ฅผ ๋์น ์ ์์ |
| 8 | +var exist = function (board, word) { |
| 9 | + for (let y = 0; y < board.length; y++) { |
| 10 | + for (let x = 0; x < board[0].length; x++) { |
| 11 | + // ์์์ด ๋๋ ๋จ์ด๋ฅผ ๋ง์ฃผ์น๋ฉด dfs ๋๋ ค๋ณด๊ธฐ |
| 12 | + if (board[y][x] === word[0] && dfs(board, y, x, word, 0)) { |
| 13 | + return true; |
| 14 | + } |
| 15 | + } |
| 16 | + } |
| 17 | + return false; |
| 18 | +}; |
| 19 | + |
| 20 | +function dfs(board, y, x, word, index) { |
| 21 | + // ์ฑ๊ณต ์กฐ๊ฑด: ๋ชจ๋ ๋ฌธ์๋ฅผ ์ฐพ์์ ๋ |
| 22 | + if (index === word.length) return true; |
| 23 | + |
| 24 | + // ์คํจ ์กฐ๊ฑด: ๋ฒ์๋ฅผ ๋ฒ์ด๋๊ฑฐ๋ ํ์ฌ ๊ธ์๊ฐ ์ผ์นํ์ง ์์ ๋ |
| 25 | + if ( |
| 26 | + y < 0 || |
| 27 | + y >= board.length || |
| 28 | + x < 0 || |
| 29 | + x >= board[0].length || |
| 30 | + board[y][x] !== word[index] |
| 31 | + ) { |
| 32 | + return false; |
| 33 | + } |
| 34 | + |
| 35 | + // ํ์ฌ ์
์ฌ์ฉ ํ์ |
| 36 | + const temp = board[y][x]; |
| 37 | + board[y][x] = true; // ์์ ๋ฐฉ๋ฌธ ํ์ |
| 38 | + |
| 39 | + // ์ํ์ข์ฐ ํ์, ํ๋๋ผ๋ ์ฐพ๊ฒ๋๋ค๋ฉด true |
| 40 | + const found = |
| 41 | + dfs(board, y + 1, x, word, index + 1) || |
| 42 | + dfs(board, y - 1, x, word, index + 1) || |
| 43 | + dfs(board, y, x + 1, word, index + 1) || |
| 44 | + dfs(board, y, x - 1, word, index + 1); |
| 45 | + |
| 46 | + // ์๋ ๊ฐ์ผ๋ก ๋ณต์ (๋ฐฑํธ๋ํน) |
| 47 | + board[y][x] = temp; |
| 48 | + |
| 49 | + return found; |
| 50 | +} |
0 commit comments