36. Valid Sudoku
Problem
Tags: Array
, Hash Table
, Matrix
Determine if a 9 x 9
Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
- Each row must contain the digits
1-9
without repetition. - Each column must contain the digits
1-9
without repetition. - Each of the nine
3 x 3
sub-boxes of the grid must contain the digits1-9
without repetition.
Note:
- A Sudoku board (partially filled) could be valid but is not necessarily solvable.
- Only the filled cells need to be validated according to the mentioned rules.
Example 1:
Input: board =
[["5","3",".",".","7",".",".",".","."]
,["6",".",".","1","9","5",".",".","."]
,[".","9","8",".",".",".",".","6","."]
,["8",".",".",".","6",".",".",".","3"]
,["4",".",".","8",".","3",".",".","1"]
,["7",".",".",".","2",".",".",".","6"]
,[".","6",".",".",".",".","2","8","."]
,[".",".",".","4","1","9",".",".","5"]
,[".",".",".",".","8",".",".","7","9"]]
Output: true
Example 2:
Input: board =
[["8","3",".",".","7",".",".",".","."]
,["6",".",".","1","9","5",".",".","."]
,[".","9","8",".",".",".",".","6","."]
,["8",".",".",".","6",".",".",".","3"]
,["4",".",".","8",".","3",".",".","1"]
,["7",".",".",".","2",".",".",".","6"]
,[".","6",".",".",".",".","2","8","."]
,[".",".",".","4","1","9",".",".","5"]
,[".",".",".",".","8",".",".","7","9"]]
Output: false
Explanation: Same as Example 1, except with the 5 in the top left corner being modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid.
Constraints:
board.length == 9
board[i].length == 9
board[i][j]
is a digit1-9
or'.'
.
Code
JS
// 36. Valid Sudoku (6/29/53723)
// Runtime: 121 ms (30.78%) Memory: 40.96 MB (94.91%)
/**
* @param {character[][]} board
* @return {boolean}
*/
function isValidSudoku(board) {
function validateBox(X, Y) {
let s = new Set(), c = 0;
for(let i = 0; i < 3; i++)
for(let j = 0; j < 3; j++)
if(board[X*3 + i][Y*3 + j] !== ".") {
c++;
s.add(board[X*3 + i][Y*3 + j]);
}
return s.size === c;
}
function validateRow(n) {
let s = new Set(), c = 0;
for(let i = 0; i < 9; i++)
if(board[n][i] !== ".") {
c++;
s.add(board[n][i]);
}
return s.size === c;
}
function validateCol(n) {
let s = new Set(), c = 0;
for(let i = 0; i < 9; i++)
if(board[i][n] !== ".") {
c++;
s.add(board[i][n]);
}
return s.size === c;
}
for(let i = 0; i < 3; i++)
for(let j = 0; j < 3; j++)
if(!validateBox(i, j)) return false;
for(let i = 0; i < 9; i++)
if(!validateRow(i)) return false;
for(let i = 0; i < 9; i++)
if(!validateCol(i)) return false;
return true;
};