Facebook
From Faisal, 1 Week ago, written in JavaScript.
Embed
Download Paste or View Raw
Hits: 118
  1. const sudokuGrid = [
  2.   [5, 3, 0, 0, 7, 0, 0, 0, 0],
  3.   [6, 0, 0, 1, 9, 5, 0, 0, 0],
  4.   [0, 9, 8, 0, 0, 0, 0, 6, 0],
  5.   [8, 0, 0, 0, 6, 0, 0, 0, 3],
  6.   [4, 0, 0, 8, 0, 3, 0, 0, 1],
  7.   [7, 0, 0, 0, 2, 0, 0, 0, 6],
  8.   [0, 6, 0, 0, 0, 0, 2, 8, 0],
  9.   [0, 0, 0, 4, 1, 9, 0, 0, 5],
  10.   [0, 0, 0, 0, 8, 0, 0, 7, 9]
  11. ];
  12.  
  13. function solveSudoku(grid) {
  14.  //iterate over every cell in grid
  15.   for (let row = 0; row < 9; row++) {
  16.     for (let col = 0; col < 9; col++) {
  17.       if (grid[row][col] === 0) {
  18.         for (let num = 1; num <= 9; num++) {
  19.  //check if num can be placed in current cell
  20.           if (isValid(grid, row, col, num)) {
  21.             grid[row][col] = num;
  22.  
  23.             if (solveSudoku(grid)) {
  24.               return grid;
  25.             }
  26.  
  27.             grid[row][col] = 0;
  28.           }
  29.         }
  30.         return false;
  31.       }
  32.     }
  33.   }
  34.  //if prgram doesnt break before reaching here, all cells are filled
  35.   return true;
  36. }
  37.  
  38. console.log(solveSudoku(sudokuGrid));