Skip to content

Commit a64f4fc

Browse files
authored
Create 37-sudoku-solver.js
1 parent 0b7fbc6 commit a64f4fc

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

37-sudoku-solver.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* @param {character[][]} board
3+
* @return {void} Do not return anything, modify board in-place instead.
4+
*/
5+
const solveSudoku = function(board) {
6+
dfs(0, 0)
7+
function dfs(row, col) {
8+
if (row === 9) return true
9+
if (col === 9) return dfs(row + 1, 0)
10+
if (board[row][col] === ".") {
11+
for (let num = 1; num <= 9; num++) {
12+
if (isValid(row, col, `${num}`)) {
13+
board[row][col] = `${num}`
14+
if (dfs(row, col + 1)) return true
15+
board[row][col] = "."
16+
}
17+
}
18+
} else {
19+
return dfs(row, col + 1)
20+
}
21+
return false
22+
}
23+
function isValid(row, col, num) {
24+
for (let rowIdx = 0; rowIdx < 9; rowIdx++) if (board[rowIdx][col] === num) return false
25+
for (let colIdx = 0; colIdx < 9; colIdx++) if (board[row][colIdx] === num) return false
26+
27+
let squareRowStart = row - (row % 3)
28+
let squareColStart = col - (col % 3)
29+
for (let rIdx = 0; rIdx < 3; rIdx++) {
30+
for (let cIdx = 0; cIdx < 3; cIdx++) {
31+
if (board[squareRowStart + rIdx][squareColStart + cIdx] === num) return false
32+
}
33+
}
34+
return true
35+
}
36+
}

0 commit comments

Comments
 (0)