-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path36.valid-sudoku.ts
32 lines (26 loc) · 931 Bytes
/
36.valid-sudoku.ts
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
function isValidSudoku(board: string[][]): boolean {
const rows = new Map<number, Set<string>>();
const columns = new Map<number, Set<string>>();
const boxes = new Map<string, Set<string>>();
for (let i = 0; i < board.length; i++) {
for (let j = 0; j < board[i].length; j++) {
const value = board[i][j];
if (value === ".") continue;
const row = i;
const column = j;
const box = [Math.floor(i / 3), Math.floor(j / 3)].join(",");
const rowSet = rows.get(row) ?? new Set();
const columnSet = columns.get(column) ?? new Set();
const boxSet = boxes.get(box) ?? new Set();
if (rowSet.has(value) || columnSet.has(value) || boxSet.has(value))
return false;
rowSet.add(value);
rows.set(row, rowSet);
columnSet.add(value);
columns.set(column, columnSet);
boxSet.add(value);
boxes.set(box, boxSet);
}
}
return true;
}