-
Notifications
You must be signed in to change notification settings - Fork 0
/
SudokuUtil.js
97 lines (91 loc) · 2.08 KB
/
SudokuUtil.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import { Util } from "./Util.js";
const SudokuUtil = {
isValidPuzzle: function (grid) {
for (let i = 0; i < grid.length; i++) {
if (!isValidRow(grid, i)) {
return false;
}
if (!isValidCol(grid, i)) {
return false;
}
}
if (!isValidBox(grid)) {
return false;
}
return true;
},
isValidPlace: function (grid, row, col, number) {
for (let i = 0; i < 9; i++) {
if (grid[i][col] === number) {
return false;
}
}
for (let i = 0; i < 9; i++) {
if (grid[row][i] === number) {
return false;
}
}
let localBoxRow = row - (row % 3);
let localBoxCol = col - (col % 3);
for (let i = localBoxRow; i < localBoxRow + 3; i++) {
for (let j = localBoxCol; j < localBoxCol + 3; j++) {
if (grid[i][j] === number) {
return false;
}
}
}
return true;
},
};
function isValidRow(grid, row) {
let set = new Set();
for (let i = 0; i < 9; i++) {
let number = grid[row][i];
if (number < 0 || number > 9) {
return false;
}
if (set.has(number)) {
return false;
} else {
number !== 0 && set.add(number);
}
}
return true;
}
function isValidCol(grid, col) {
let set = new Set();
for (let i = 0; i < 9; i++) {
let number = grid[i][col];
if (number < 0 || number > 9) {
return false;
}
if (set.has(number)) {
return false;
} else {
number !== 0 && set.add(number);
}
}
return true;
}
function isValidBox(grid) {
for (let row = 0; row < grid.length; row += 3) {
for (let col = 0; col < grid.length; col += 3) {
let set = new Set();
for (let subRow = 0; subRow < 3; subRow++) {
for (let subCol = 0; subCol < 3; subCol++) {
let number = grid[subRow][subCol];
if (number < 0 || number > 9) {
return false;
}
if (set.has(number)) {
return false;
} else {
number !== 0 && set.add(number);
}
}
}
}
}
return true;
}
export { SudokuUtil };