-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsudoku.js
63 lines (52 loc) · 1.73 KB
/
sudoku.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
// matrix 9*9
// https://jsbin.com/paminob/edit?js,console
// In place mutates board param
const solveSudoku = function (board) {
const original = JSON.parse(JSON.stringify(board));
const checkSquare = (grid, row, col) => {
let n = Math.sqrt(size);
row = (Math.ceil(row / n) * n) - n;
col = (Math.ceil(col / n) * n) - n;
const h = {};
for (let r = 0; r < n; r++) {
for (let c = 0; c < n; c++) {
const val = grid[row + r][col + c];
if (val !== '.' && h[val]) return false;
h[val] = val;
}
}
return true;
};
const valid = (board, r, c) => {
let hash = {};
for (let h = 0; h < board.length; h++) {
if (board[r][h] !== '.' && hash[board[r][h]]) return false;
hash[board[r][h]] = true;
}
hash = {};
for (let v = 0; v < board[0].length; v++) {
if (board[v][c] !== '.' && hash[board[v][c]]) return false;
hash[board[v][c]] = true;
}
return checkSquare(board, r + 1, c + 1);
};
const solve = (board, r = 0, c = 0) => {
for (let i = 1; i < 10; i++) {
if (original[r][c] === '.') board[r][c] = i;
let nextC = c + 1;
let nextR = r;
if (nextC >= board[0].length) {
nextC = 0;
nextR++;
};
if (nextR >= board.length) return valid(board, r, c);
if (valid(board, r, c)) {
if (solve(board, nextR, nextC)) return true;
} else {
if (original[r][c] === '.') board[r][c] = '.';
}
}
return false;
}
return solve(board);
};