Created
August 31, 2023 06:18
-
-
Save IAmAnubhavSaini/b9b75673cf96fc92f48e6c0c2af2ca9f to your computer and use it in GitHub Desktop.
36. valid sudoku
This file contains 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
/** | |
* @param {character[][]} board | |
* @return {boolean} | |
*/ | |
var isValidSudoku = function(board) { | |
toString(board); | |
const len = board.length; | |
let valid = true; | |
for(let i = 0; i < len && valid; i++) { | |
valid = valid && isValidRow(board, i) && isValidColumn(board, i); | |
} | |
for(let i = 0; i < 3 && valid; i++) { | |
for(let j = 0; j < 3 && valid; j++) { | |
valid = valid && isValid9(board, i, j); | |
} | |
} | |
return valid; | |
}; | |
function isValidRow(board, row) { | |
const len = board.length; | |
const s = new Set(); | |
for(let i = 0; i < len; i++) { | |
const n = board[row][i]; | |
if(!isNum(n)) { | |
continue | |
} | |
if(s.has(n)) { | |
return false; | |
} | |
s.add(n); | |
} | |
return true; | |
} | |
function isValidColumn(board, col) { | |
const len = board.length; | |
const s = new Set(); | |
for(let i = 0; i < len; i++) { | |
const n = board[i][col]; | |
if(!isNum(n)) { | |
continue | |
} | |
if(s.has(n)){ | |
return false; | |
} | |
s.add(n); | |
} | |
return true; | |
} | |
function isValid9(board, x, y) { | |
const s = new Set(); | |
const r = x * 3; | |
const c = y * 3; | |
for(let i = r; i < r + 3; i++) { | |
for(let j = c; j < c + 3; j++) { | |
const n = board[i][j]; | |
if(!isNum(n)) { | |
continue | |
} | |
if(s.has(n)) { | |
return false; | |
} | |
s.add(n); | |
console.log({x, y, i, j, s}); | |
} | |
} | |
return true; | |
} | |
function isNum(x) { | |
return x >= '0' && x <= '9'; | |
} | |
function toString(board) { | |
const len = board.length; | |
for(let i = 0; i < len; i++) { | |
let s = ''; | |
for(let j = 0; j < len; j++) { | |
s += board[i][j].padStart(3, ' '); | |
} | |
console.log(s); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment