-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathisValidSudoku.js
More file actions
75 lines (67 loc) · 2.49 KB
/
isValidSudoku.js
File metadata and controls
75 lines (67 loc) · 2.49 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
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
// Valid Sudoku
// You are given a a 9 x 9 Sudoku board board. A Sudoku board is valid if the following rules are followed:
// Each row must contain the digits 1-9 without duplicates.
// Each column must contain the digits 1-9 without duplicates.
// Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without duplicates.
// Return true if the Sudoku board is valid, otherwise return false
// Note: A board does not need to be full or be solvable to be valid.
class Solution {
/**
* @param {character[][]} board
* @return {boolean}
*/
isValidSudoku(board) {
const cols = new Map();
const rows = new Map();
const squares = new Map(); // key = (r / 3) * 3 + c / 3
for (let r = 0; r < 9; r++) {
for (let c = 0; c < 9; c++) {
const cell = board[r][c];
if (cell === '.') {
continue;
}
if (
rows.get(r)?.has(cell) ||
cols.get(c)?.has(cell) ||
squares
.get(Math.floor(r / 3) * 3 + Math.floor(c / 3))
?.has(cell)
) {
return false;
}
cols.set(c, new Set(cols.get(c)).add(cell));
rows.set(r, new Set(rows.get(r)).add(cell));
squares.set(
Math.floor(r / 3) * 3 + Math.floor(c / 3),
new Set(
squares.get(Math.floor(r / 3) * 3 + Math.floor(c / 3)),
).add(cell),
);
}
}
return true;
}
}
const solution = new Solution();
// Example 1
let board1 =
[["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"]]; // true
let board2 =
[["1","2",".",".","3",".",".",".","."],
["4",".",".","5",".",".",".",".","."],
[".","9","1",".",".",".",".",".","3"],
["5",".",".",".","6",".",".",".","4"],
[".",".",".","8",".","3",".",".","5"],
["7",".",".",".","2",".",".",".","6"],
[".",".",".",".",".",".","2",".","."],
[".",".",".","4","1","9",".",".","8"],
[".",".",".",".","8",".",".","7","9"]]; // False
console.log(solution.isValidSudoku(board1));