-
Notifications
You must be signed in to change notification settings - Fork 6
/
36. Valid Sudoku.js
55 lines (52 loc) · 1.12 KB
/
36. Valid 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
/**
* @param {character[][]} board
* @return {boolean}
*/
const nums = [".", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
function isUnique(arr) {
const map = {};
for(let i = 0; i < arr.length; i++) {
if (nums.indexOf(arr[i]) === -1) {
return false;
}
if (arr[i] !== "." && map[arr[i]] !== undefined) {
return false;
}
map[arr[i]] = 0;
}
return true;
}
var isValidSudoku = function(board) {
// rows
for (let i = 0; i < board.length; i++) {
if (!isUnique(board[i])) {
return false;
}
}
// cols
for (let i = 0; i < board.length; i++) {
const temp = [];
for (let j = 0; j < board[0].length; j++) {
temp.push(board[j][i]);
}
if (!isUnique(temp)) {
return false;
}
}
// cubes
const third = board.length / 3;
for (let i = 0; i < third; i++) {
for (let j = 0; j < third; j++) {
const temp = [];
for (let k = 0; k < third; k++) {
for (let l = 0; l < third; l++) {
temp.push(board[3 * i + k][3 * j + l]);
}
}
if (!isUnique(temp)) {
return false;
}
}
}
return true;
};