有9×9数量不变数独用二维数组表示,检查数独是否满足以下条件:
- 数字1-9每行只能出现一次
- 数字1-9每列只能出现一次
- 数字1-9每3×3的框内只能出现一次
数独空白部分用‘.’填充,列子如下
var a = [
["5","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
["7",".",".",".","2",".",".",".","6"],
[".","6",".",".",".",".","2","8","."],
[".",".",".","4","1","9",".",".","5"],
[".",".",".",".","8",".",".","7","9"]
]
只验证上面数独是否满足要求,并不需要验证数独是否可解,代码如下所示
/**
* @param {String[][]} board
* @return {boolean}
*/
let isValidSudoku = function(board) {
for (let i = 0; i < 9; i++) {
let row = new Set();
let column = new Set();
let block = new Set();
for(let j = 0;j < 9; j++) {
if (board[i][j] !== '.') {
let current_row = board[i][j];
if (row.has(current_row)) {
console.log('row',i,j,current_row, row);
return false;
}else {
row.add(current_row);
}
}
if (board[j][i] !== '.') {
let current_col = board[j][i];
if (column.has(current_col)) {
console.log('column',i,j,current_col, column);
return false;
}else {
column.add(current_col);
}
}
let x = (+(i/3).toString()[0])*3 + (+(j/3).toString()[0]);
let y = (i%3)*3 + j%3;
let current_blo = board[x][y];
if (current_blo !== '.') {
if (block.has(current_blo)) {
console.log('block',i,j,current_blo, block);
return false;
} else {
block.add(current_blo);
}
}
}
}
return true;
};
基本思路是利用set数据结构验证数字每一行每一列以及每一块儿是否存在重复数字,其中验证块较为复杂点,需要找到对应i,j的关系,并且js中除法运算不是取整,因此要手动取整