-
-
Notifications
You must be signed in to change notification settings - Fork 164
/
Copy pathvalidSudoku.js
53 lines (44 loc) · 1.81 KB
/
validSudoku.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
function isValidSuduko(board){
let rowsMap = new Map();
let colsMap = new Map();
let squaresMap = new Map();
for (let r = 0; r < board.length; r++) {
for (let c = 0; c < board[0].length; c++) {
const cell = board[r][c];
if(cell === '.') {
continue;
}
if(rowsMap.get(r)?.has(cell)
|| colsMap.get(c)?.has(cell)
|| squaresMap.get(Math.floor(r/3)*3+Math.floor(c/3))?.has(cell)) {
return false;
}
rowsMap.set(r, new Set(rowsMap.get(r)).add(cell));
colsMap.set(c, new Set(colsMap.get(c)).add(cell));
squaresMap.set(Math.floor(r/3)*3+Math.floor(c/3), new Set(squaresMap.get(Math.floor(r/3)*3+Math.floor(c/3))).add(cell));
}
}
return true;
}
const board1 =
[['2','1','.','.','4','.','.','.','.'],
['3','.','.','5','.','.','.','.','.'],
['.','9','8','.','.','.','.','.','3'],
['5','.','.','.','6','.','.','.','4'],
['.','.','.','8','.','3','.','.','5'],
['7','.','.','.','2','.','.','.','6'],
['.','.','.','.','.','.','2','.','.'],
['.','.','.','4','1','9','.','.','8'],
['.','.','.','.','8','.','.','7','1']];
const board2 =
[['2','1','.','.','4','.','.','.','.'],
['3','.','.','5','.','.','.','.','.'],
['.','9','2','.','.','.','.','.','3'],
['5','.','.','.','6','.','.','.','4'],
['.','.','.','8','.','3','.','.','5'],
['7','.','.','.','2','.','.','.','6'],
['.','.','.','.','.','.','2','.','.'],
['.','.','.','4','1','9','.','.','8'],
['.','.','.','.','8','.','.','7','1']];
console.log(isValidSuduko(board1));
console.log(isValidSuduko(board2));