mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 00:01:37 +08:00
Added: Sodoko Solver In DP (#420)
* Added: Sodoko Solver In DP * added: space remove * Chnage code accoding to npm standards. * Change * Update: All Issue Fix * Update SudokuSolver.js Co-authored-by: vinayak <itssvinayak@gmail.com>
This commit is contained in:
50
Dynamic-Programming/SudokuSolver.js
Normal file
50
Dynamic-Programming/SudokuSolver.js
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
const _board = [
|
||||||
|
['.', '9', '.', '.', '4', '2', '1', '3', '6'],
|
||||||
|
['.', '.', '.', '9', '6', '.', '4', '8', '5'],
|
||||||
|
['.', '.', '.', '5', '8', '1', '.', '.', '.'],
|
||||||
|
['.', '.', '4', '.', '.', '.', '.', '.', '.'],
|
||||||
|
['5', '1', '7', '2', '.', '.', '9', '.', '.'],
|
||||||
|
['6', '.', '2', '.', '.', '.', '3', '7', '.'],
|
||||||
|
['1', '.', '.', '8', '.', '4', '.', '2', '.'],
|
||||||
|
['7', '.', '6', '.', '.', '.', '8', '1', '.'],
|
||||||
|
['3', '.', '.', '.', '9', '.', '.', '.', '.']
|
||||||
|
]
|
||||||
|
|
||||||
|
const isValid = (board, row, col, k) => {
|
||||||
|
for (let i = 0; i < 9; i++) {
|
||||||
|
const m = 3 * Math.floor(row / 3) + Math.floor(i / 3)
|
||||||
|
const n = 3 * Math.floor(col / 3) + i % 3
|
||||||
|
if (board[row][i] === k || board[i][col] === k || board[m][n] === k) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
const sodokoSolver = (data) => {
|
||||||
|
for (let i = 0; i < 9; i++) {
|
||||||
|
for (let j = 0; j < 9; j++) {
|
||||||
|
if (data[i][j] === '.') {
|
||||||
|
for (let k = 1; k <= 9; k++) {
|
||||||
|
if (isValid(data, i, j, k)) {
|
||||||
|
data[i][j] = `${k}`
|
||||||
|
if (sodokoSolver(data)) {
|
||||||
|
return true
|
||||||
|
} else {
|
||||||
|
data[i][j] = '.'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// testing
|
||||||
|
(() => {
|
||||||
|
if (sodokoSolver(_board)) {
|
||||||
|
console.log(_board)
|
||||||
|
}
|
||||||
|
})()
|
Reference in New Issue
Block a user