Skip to content

Commit ad69750

Browse files
authored
Update 37-sudoku-solver.js
1 parent 827515e commit ad69750

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

37-sudoku-solver.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,46 @@ const solveSudoku = function(board) {
3434
return true
3535
}
3636
}
37+
38+
39+
// another
40+
41+
/**
42+
* @param {character[][]} board
43+
* @return {void} Do not return anything, modify board in-place instead.
44+
*/
45+
const solveSudoku = function(board) {
46+
helper(board, 0 , 0)
47+
};
48+
49+
function helper(board, row, col) {
50+
for(let i = row, m = board.length; i < m; i++, col = 0) {
51+
for(let j = col, n = board[0].length; j < n; j++) {
52+
if(board[i][j] !== '.') continue
53+
for(let k = 1; k <= 9; k++) {
54+
const ch = `${k}`
55+
const res = valid(board, i, j, ch)
56+
if(res) {
57+
board[i][j] = ch
58+
if(helper(board, i, j + 1)) return true
59+
else {
60+
board[i][j] = '.'
61+
}
62+
}
63+
}
64+
return false
65+
}
66+
}
67+
return true
68+
}
69+
70+
71+
function valid(board, row, col, ch) {
72+
const blkRow = ~~(row / 3), blkCol = ~~(col / 3)
73+
for(let i = 0; i < 9; i++) {
74+
if(board[row][i] === ch) return false
75+
if(board[i][col] === ch) return false
76+
if(board[blkRow * 3 + Math.floor(i / 3)][blkCol * 3 + (i % 3)] === ch) return false
77+
}
78+
return true
79+
}

0 commit comments

Comments
 (0)