|
| 1 | +/** |
| 2 | + * https://leetcode.com/problems/sudoku-solver/description/ |
| 3 | + * Difficulty:Hard |
| 4 | + * |
| 5 | + * Write a program to solve a Sudoku puzzle by filling the empty cells. |
| 6 | + * Empty cells are indicated by the character '.'. |
| 7 | + * You may assume that there will be only one unique solution. |
| 8 | + */ |
| 9 | + |
| 10 | +/** |
| 11 | + *@param {character[][]} board |
| 12 | + *@return {void} Do not return anything, modify board in-place instead. |
| 13 | + */ |
| 14 | +varsolveSudoku=function(board){ |
| 15 | +solve(board); |
| 16 | +console.log(board); |
| 17 | +}; |
| 18 | + |
| 19 | +functionsolve(board){ |
| 20 | +for(vari=0;i<9;i++){ |
| 21 | +for(varj=0;j<9;j++){ |
| 22 | +varch=board[i][j]; |
| 23 | +if(ch==='.'){ |
| 24 | +for(vark=1;k<=9;k++){ |
| 25 | + |
| 26 | +if(isValid(i,j,board,''+k)){ |
| 27 | + |
| 28 | +board[i][j]=''+k; |
| 29 | +// console.log(board); |
| 30 | +// console.log('-------------'); |
| 31 | +if(solve(board)){ |
| 32 | +// console.log(board); |
| 33 | +// console.log('-------------'); |
| 34 | +returntrue; |
| 35 | +}else{ |
| 36 | +board[i][j]='.'; |
| 37 | +} |
| 38 | +} |
| 39 | +} |
| 40 | +returnfalse; |
| 41 | +} |
| 42 | +} |
| 43 | +} |
| 44 | +returntrue; |
| 45 | +} |
| 46 | + |
| 47 | +functionisValid(row,col,board,t){ |
| 48 | + |
| 49 | +for(vari=0;i<9;i++){ |
| 50 | +varch=board[row][i]; |
| 51 | +if(ch===t)returnfalse; |
| 52 | + |
| 53 | +ch=board[i][col]; |
| 54 | +if(ch===t)returnfalse; |
| 55 | + |
| 56 | +ch=board[Math.floor(row/3)*3+Math.floor(i/3)][Math.floor(col/3)*3+i%3]; |
| 57 | +// if (row === 0 && col === 8) { |
| 58 | +// console.log('~ ', Math.floor(row / 3) * 3 + Math.floor(i / 3), Math.floor(row / 3) * 3 + i % 3, ch); |
| 59 | +// } |
| 60 | +if(ch===t)returnfalse; |
| 61 | +} |
| 62 | +returntrue; |
| 63 | + |
| 64 | +} |
| 65 | + |
| 66 | +console.log(solveSudoku([ |
| 67 | +[".",".","9","7","4","8",".",".","."], |
| 68 | +["7",".",".",".",".",".",".",".","."], |
| 69 | +[".","2",".","1",".","9",".",".","."], |
| 70 | +[".",".","7",".",".",".","2","4","."], |
| 71 | +[".","6","4",".","1",".","5","9","."], |
| 72 | +[".","9","8",".",".",".","3",".","."], |
| 73 | +[".",".",".","8",".","3",".","2","."], |
| 74 | +[".",".",".",".",".",".",".",".","6"], |
| 75 | +[".",".",".","2","7","5","9",".","."] |
| 76 | +])); |
| 77 | + |
| 78 | +console.log([ |
| 79 | +["5","1","9","7","4","8","6","3","2"], |
| 80 | +["7","8","3","6","5","2","4","1","9"], |
| 81 | +["4","2","6","1","3","9","8","7","5"], |
| 82 | +["3","5","7","9","8","6","2","4","1"], |
| 83 | +["2","6","4","3","1","7","5","9","8"], |
| 84 | +["1","9","8","5","2","4","3","6","7"], |
| 85 | +["9","7","5","8","6","3","1","2","4"], |
| 86 | +["8","3","2","4","9","1","7","5","6"], |
| 87 | +["6","4","1","2","7","5","9","8","3"] |
| 88 | +]) |