-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathisValidSudoku.ts
More file actions
49 lines (43 loc) · 1.21 KB
/
isValidSudoku.ts
File metadata and controls
49 lines (43 loc) · 1.21 KB
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
function isValidSudoku(board: string[][]): boolean {
const rows = {};
const columns = {};
const squares = {};
for (let r = 0; r < 9; r++) {
for (let c = 0; c < 9; c++) {
let num = board[r][c];
if (num === '.') {
continue;
}
const grid = `${Math.floor(r / 3)}${Math.floor(c / 3)}`;
if (!rows[r]) {
rows[r] = new Set();
}
if (!columns[c]) {
columns[c] = new Set();
}
if (!squares[grid]) {
squares[grid] = new Set();
}
if (rows[r].has(num) || columns[c].has(num) || squares[grid].has(num)) {
return false;
}
columns[c].add(num);
rows[r].add(num);
squares[grid].add(num);
}
}
return true;
}
console.log(
isValidSudoku([
['1', '2', '.', '.', '3', '.', '.', '.', '.'],
['4', '.', '.', '5', '.', '.', '.', '.', '.'],
['.', '9', '8', '.', '.', '.', '.', '.', '3'],
['5', '.', '.', '.', '6', '.', '.', '.', '4'],
['.', '.', '.', '8', '.', '3', '.', '.', '5'],
['7', '.', '.', '.', '2', '.', '.', '.', '6'],
['.', '.', '.', '.', '.', '.', '2', '.', '.'],
['.', '.', '.', '4', '1', '9', '.', '.', '8'],
['.', '.', '.', '.', '8', '.', '.', '7', '9'],
])
);