Skip to content

Instantly share code, notes, and snippets.

@germanescobar
Created August 21, 2021 00:15
Show Gist options
  • Save germanescobar/e3ff10be3fef375d49e0aa458f2e00e6 to your computer and use it in GitHub Desktop.
Save germanescobar/e3ff10be3fef375d49e0aa458f2e00e6 to your computer and use it in GitHub Desktop.
var isValidSudoku = function(board) {
for (let i=0; i < board.length; i++) {
if (!isValidColumn(board, i) || !isValidRow(board, i) || !isValidSubBox(board, i)) {
return false
}
}
return true
};
function isValidColumn(board, col) {
const nums = new Set()
for (let i=0; i < board.length; i++) {
const num = board[i][col]
if (nums.has(num)) return false
if (num !== ".") nums.add(num)
}
return true
}
function isValidRow(board, row) {
const nums = new Set()
for (let i=0; i < board.length; i++) {
const num = board[row][i]
if (nums.has(num)) return false
if (num !== ".") nums.add(num)
}
return true
}
function isValidSubBox(board, index) {
const row = Math.floor(index/3) * 3
const col = (index % 3) * 3
const nums = new Set()
for (let i=row; i < row + 3; i++) {
for (let j=col; j < col + 3; j++) {
const num = board[i][j]
if (nums.has(num)) return false
if (num !== ".") nums.add(num)
}
}
return true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment