|
| 1 | +const UNASSIGNED = 0; |
| 2 | + |
| 3 | +/* Returns a boolean which indicates whether any assigned entry |
| 4 | + in the specified row matches the given number. */ |
| 5 | +function usedInRow(grid, row, num) { |
| 6 | + for (let col = 0; col < grid.length; col++) { |
| 7 | + if (grid[row][col] === num) { |
| 8 | + return true; |
| 9 | + } |
| 10 | + } |
| 11 | + return false; |
| 12 | +} |
| 13 | +/* Returns a boolean which indicates whether any assigned entry |
| 14 | + in the specified column matches the given number. */ |
| 15 | +function usedInCol(grid, col, num) { |
| 16 | + for (let row = 0; row < grid.length; row++) { |
| 17 | + if (grid[row][col] === num) { |
| 18 | + return true; |
| 19 | + } |
| 20 | + } |
| 21 | + return false; |
| 22 | +} |
| 23 | +/* Returns a boolean which indicates whether any assigned entry |
| 24 | + within the specified 3x3 box matches the given number. */ |
| 25 | +function usedInBox(grid, boxStartRow, boxStartCol, num) { |
| 26 | + for (let row = 0; row < 3; row++) { |
| 27 | + for (let col = 0; col < 3; col++) { |
| 28 | + if (grid[row + boxStartRow][col + boxStartCol] === num) { |
| 29 | + return true; |
| 30 | + } |
| 31 | + } |
| 32 | + } |
| 33 | + return false; |
| 34 | +} |
| 35 | + |
| 36 | +function isSafe(grid, row, col, num) { |
| 37 | + /* Check if 'num' is not already placed in current row, |
| 38 | + current column and current 3x3 box */ |
| 39 | + return ( |
| 40 | + !usedInRow(grid, row, num) && |
| 41 | + !usedInCol(grid, col, num) && |
| 42 | + !usedInBox(grid, row - (row % 3), col - (col % 3), num) |
| 43 | + ); |
| 44 | +} |
| 45 | +function solveSudoku(grid) { |
| 46 | + let row = 0; |
| 47 | + let col = 0; |
| 48 | + let checkBlankSpaces = false; |
| 49 | + // If there is no unassigned location, we are done |
| 50 | + for (row = 0; row < grid.length; row++) { |
| 51 | + for (col = 0; col < grid[row].length; col++) { |
| 52 | + if (grid[row][col] === UNASSIGNED) { |
| 53 | + checkBlankSpaces = true; |
| 54 | + break; |
| 55 | + } |
| 56 | + } |
| 57 | + if (checkBlankSpaces === true) { |
| 58 | + break; |
| 59 | + } |
| 60 | + } |
| 61 | + if (checkBlankSpaces === false) { |
| 62 | + return true; |
| 63 | + } // success! |
| 64 | + // consider digits 1 to 9 |
| 65 | + for (let num = 1; num <= 9; num++) { |
| 66 | + // if looks promising |
| 67 | + if (isSafe(grid, row, col, num)) { |
| 68 | + // make tentative assignment |
| 69 | + grid[row][col] = num; |
| 70 | + // return, if success, yay! |
| 71 | + if (solveSudoku(grid)) { |
| 72 | + return true; |
| 73 | + } |
| 74 | + // failure, unmake & try again |
| 75 | + grid[row][col] = UNASSIGNED; |
| 76 | + } |
| 77 | + } |
| 78 | + return false; |
| 79 | +} |
| 80 | + |
| 81 | +export function sudokuSolver(grid) { |
| 82 | + if (solveSudoku(grid) === true) { |
| 83 | + return grid; |
| 84 | + } |
| 85 | + return 'NO SOLUTION EXISTS!'; |
| 86 | +} |
0 commit comments