这是一个力扣上的算法题, 判断一个数组是否为有效数独, 当时看到题解就挺震惊的, 所以依葫芦画瓢记录一下
来源:力扣 (LeetCode)
链接:leetcode-cn.com/leetbook/re…
有效的数独
请你判断一个 9 x 9 的数独是否有效。只需要 根据以下规则 ,验证已经填入的数字是否有效即可。
- 数字 1-9 在每一行只能出现一次
- 数字 1-9 在每一列只能出现一次
- 数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次
注意:
- 一个有效的数独(部分已被填充)不一定是可解的
- 只需要根据以上规则,验证已经填入的数字是否有效即可
- 空白格用 '.' 表示 当时看到题有点蒙, 知道需要三个数组来判断, 但具体怎么判断不知道, 然后看到了位算法题解
/**
* @param {character[][]} board
* @return {boolean}
*/
var isValidSudoku = function (board) {
var row = [], col = [], box = [], shift = 0, boxInd = 0
for (var i = 0; i < 9; i++) {
for (var j = 0; j < 9; j++) {
if (board[i][j] == '.') continue
boxInd = Math.floor(i / 3) * 3 + Math.floor(j / 3)
shift = 1 << (board[i][j] * 1)
if ((row[i] & shift) > 0 || (col[j] & shift) > 0 || (box[boxInd] & shift) > 0)
return false;
row[i] |= shift
col[j] |= shift
box[boxInd] |= shift
}
}
return true
};
位算法图示, 这里的num相当于我代码里的board[i][j]