|
| 1 | +/** |
| 2 | + * 37. Sudoku Solver |
| 3 | + * https://leetcode.com/problems/sudoku-solver/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * Write a program to solve a Sudoku puzzle by filling the empty cells. |
| 7 | + * |
| 8 | + * A sudoku solution must satisfy all of the following rules: |
| 9 | + * - Each of the digits 1-9 must occur exactly once in each row. |
| 10 | + * - Each of the digits 1-9 must occur exactly once in each column. |
| 11 | + * - Each of the digits 1-9 must occur exactly once in each of the |
| 12 | + * 9 3x3 sub-boxes of the grid. |
| 13 | + * - The '.' character indicates empty cells. |
| 14 | + */ |
| 15 | + |
| 16 | +/** |
| 17 | + * @param {character[][]} board |
| 18 | + * @return {void} Do not return anything, modify board in-place instead. |
| 19 | + */ |
| 20 | +var solveSudoku = function(board) { |
| 21 | + for (let i = 0; i < board.length; i++) { |
| 22 | + for (let j = 0; j < board.length; j++) { |
| 23 | + if (board[i][j] === '.') { |
| 24 | + for (let k = 1; k < 10; k++) { |
| 25 | + if (isValid(board, i, j, k.toString())) { |
| 26 | + board[i][j] = k.toString(); |
| 27 | + const solution = solveSudoku(board); |
| 28 | + if (solution !== false) { |
| 29 | + return solution; |
| 30 | + } |
| 31 | + board[i][j] = '.'; |
| 32 | + } |
| 33 | + } |
| 34 | + return false; |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + return board; |
| 40 | +}; |
| 41 | + |
| 42 | +function isValid(board, i, j, k) { |
| 43 | + for (let index = 0; index < board.length; index++) { |
| 44 | + if (board[i][index] === k) return false; |
| 45 | + if (board[index][j] === k) return false; |
| 46 | + const [x, y] = [ |
| 47 | + 3 * Math.floor(i / 3) + Math.floor(index / 3), |
| 48 | + 3 * Math.floor(j / 3) + index % 3, |
| 49 | + ]; |
| 50 | + if (board[x][y] === k) { |
| 51 | + return false; |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + return true; |
| 56 | +} |
0 commit comments