-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy path0037-sudoku-solver.js
79 lines (69 loc) · 1.98 KB
/
0037-sudoku-solver.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// 37. Sudoku Solver
// Hard 30%
// Write a program to solve a Sudoku puzzle by filling the empty cells.
// Empty cells are indicated by the character '.'.
// You may assume that there will be only one unique solution.
// A sudoku puzzle...
// ...and its solution numbers marked in red.
/**
* @param {character[][]} board
* @return {void} Do not return anything, modify board in-place instead.
*/
const solveSudoku = function(board) {
const solve = function(board) {
for (let i = 0; i < 9; i++) {
for (let j = 0; j < 9; j++) {
if (board[i][j] === '.') {
for (let c = 1; c <= 9; c++) {
if (isValid(board, i, j, c + '')) {
board[i][j] = c + ''
if(solve(board)) return true
else board[i][j] = '.'
}
}
return false
}
}
}
return true
}
const isValid = function(board, row, col, x) {
const trunc = Math.trunc,
p = trunc(row / 3) * 3,
q = trunc(col / 3) * 3
for (let i = 0; i < 9; i++) {
if (board[row][i] === x ||
board[i][col] === x ||
board[p + trunc(i / 3)][i % 3 + q] === x)
return false
}
return true
}
for (let i = 0; i < 9; i++) board[i] = board[i].split('')
solve(board)
for (let i = 0; i < 9; i++) board[i] = board[i].join('')
}
;[
[
"53..7....",
"6..195...",
".98....6.",
"8...6...3",
"4..8.3..1",
"7...2...6",
".6....28.",
"...419..5",
"....8..79"
],
].forEach(board => {
console.log(board)
solveSudoku(board)
console.log(board)
})
// Solution:
// 深度遍历表
// 每次碰到点(空格位),就测试该位可填的最小的数。
// 测试时,只需测试某数在该位是否合法,而不需要测试整个表。
// 当遇到某个位置没有任何数可填时,则回溯到上一个数,上一个数进行改变再测试。
// 合适就继续,不行就回溯,直到将整个表填完。
// Submission Result: Accepted