注意红框部分的事项
这里并不要求是否有解,只需要验证目前的题目是否合理
这里使用set来进行校验当前的行、列、方块里面是否存在重复的数字即可
方格的索引按照如下的排列进行标序
0 1 2
3 4 5
6 7 8
// 计算当前位置所在的方格索引
let index = Math.floor(i / 3) * 3 + Math.floor(j / 3)
var isValidSudoku = function (board) {
let rows = Array.from({ length: 9 }, () => new Set())
let cols = Array.from({ length: 9 }, () => new Set())
let boxs = Array.from({ length: 9 }, () => new Set())
for (let i = 0; i < 9; ++i) {
for (let j = 0; j < 9; ++j) {
let tmp = board[i][j]
if (tmp !== '.') {
// 计算方格的索引
let index = Math.floor(i / 3) * 3 + Math.floor(j / 3)
// 查找是否已经存在
if (rows[i].has(tmp) || cols[j].has(tmp) || boxs[index].has(tmp)) return false
// 不存在则放入set之中
rows[i].add(tmp)
cols[j].add(tmp)
boxs[index].add(tmp)
}
}
}
return true
};