请你判断一个 9 x 9 的数独是否有效。只需要 根据以下规则 ,验证已经填入的数字是否有效即可。
- 数字
1-9在每一行只能出现一次。 - 数字
1-9在每一列只能出现一次。 - 数字
1-9在每一个以粗实线分隔的3x3宫内只能出现一次。(请参考示例图)
function isValidSudoku(board: string[][]): boolean {
const row = Array.from({length:9},()=>new Array(9).fill(false))
const col = Array.from({length:9},()=>new Array(9).fill(false))
const box = Array.from({length:9},()=>new Array(9).fill(false))
for(let r = 0;r<9;r++){
for(let c = 0;c<9;c++){
const char = board[r][c]
if(char==='.') continue
const charIndex = parseInt(char) - 1
const boxIndex = Math.floor(r/3)*3 + Math.floor(c/3)
//如果 col、row、或者 box 任意一个数组中包含的有这个索引
if(row[r][charIndex] || col[r][charIndex] || box[boxIndex][charIndex]){
return false
}
row[r][charIndex] = true
col[c][charIndex] = true
box[boxIndex][charIndex] = true
}
}
return true
};