Created
August 30, 2025 17:23
-
-
Save tatsuyax25/de51eec85fd381a34cfbcff7f3159ce3 to your computer and use it in GitHub Desktop.
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Validates a partially filled 9x9 Sudoku board. | |
* Only filled cells are checked for rule violations. | |
* | |
* @param {character[][]} board - 2D array representing the Sudoku board | |
* @return {boolean} - true if the board is valid, false otherwise | |
*/ | |
var isValidSudoku = function(board) { | |
// Set to track seen digits in rows, columns, and sub-boxes | |
const seen = new Set(); | |
// Iterate over each cell in the 9x9 grid | |
for (let row = 0; row < 9; row++) { | |
for (let col = 0; col < 9; col++) { | |
const value = board[row][col]; | |
// Skip empty cells | |
if (value === '.') continue; | |
// Encode the presence of the digit in row, column, and sub-box | |
const rowKey = `row-${row}-${value}`; | |
const colKey = `col-${col}-${value}`; | |
const boxKey = `box-${Math.floor(row / 3)}-${Math.floor(col / 3)}-${value}`; | |
// If any of these keys already exist, it's a duplicate → invalid | |
if (seen.has(rowKey) || seen.has(colKey) || seen.has(boxKey)) { | |
return false; | |
} | |
// Otherwise, record the digit's presence | |
seen.add(rowKey); | |
seen.add(colKey); | |
seen.add(boxKey); | |
} | |
} | |
// No violations found | |
return true; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment