Skip to content

Commit 421cdf8

Browse files
committed
Add solution #36
1 parent 27ccb41 commit 421cdf8

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

solutions/0036-valid-sudoku.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* 36. Valid Sudoku
3+
* https://leetcode.com/problems/valid-sudoku/
4+
* Difficulty: Medium
5+
*
6+
* Determine if a 9x9 Sudoku board is valid.
7+
* Only the filled cells need to be validated according to the following rules:
8+
*
9+
* - Each row must contain the digits 1-9 without repetition.
10+
* - Each column must contain the digits 1-9 without repetition.
11+
* - Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition.
12+
*
13+
* The Sudoku board could be partially filled, where empty cells are filled with the character '.'.
14+
*/
15+
16+
/**
17+
* @param {character[][]} board
18+
* @return {boolean}
19+
*/
20+
var isValidSudoku = function(board) {
21+
const rows = new Array(9).fill().map(() => new Set());
22+
const columns = new Array(9).fill().map(() => new Set());
23+
const boxes = new Array(9).fill().map(() => new Set());
24+
25+
for (let i = 0; i < 9; i++) {
26+
for (let j = 0; j < 9; j++) {
27+
const value = board[i][j];
28+
const k = Math.floor(i / 3) * 3 + Math.floor(j / 3);
29+
const options = [rows[i], columns[j], boxes[k]];
30+
31+
if (options.some(option => option.has(value))) return false;
32+
if (value === '.') continue;
33+
options.forEach(option => option.add(value));
34+
}
35+
}
36+
37+
return true;
38+
};

0 commit comments

Comments
 (0)