|
| 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