给定一个9*9数组
判断一个 9x9 的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可。
- 数字
1-9
在每一行只能出现一次。 - 数字
1-9
在每一列只能出现一次。 - 数字
1-9
在每一个以粗实线分隔的3x3
宫内只能出现一次。
<small style="box-sizing: border-box; font-size: 12px;">上图是一个部分填充的有效的数独。</small>
数独部分空格内已填入了数字,空白格用 '.'
表示。
[
["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"]
]
说明:
- 一个有效的数独(部分已被填充)不一定是可解的。
- 只需要根据以上规则,验证已经填入的数字是否有效即可。
- 给定数独序列只包含数字
1-9
和字符'.'
。 - 给定数独永远是
9x9
形式的。
我一开始的解法
var isValidSudoku = function(board) {
let rowMapObj = {},columnMapObj = {},squareMapObj = {};
for(let i=0;i<9;i++){
for(let j=0;j<9;j++){
let item = board[i][j];
if(item === "."){
continue;
}
//验证行
if(!rowMapObj[i]) {
rowMapObj[i] = []
}
if(rowMapObj[i].includes(item)){
return false;
}
rowMapObj[i].push(item);
//验证列
if(!columnMapObj[j]) {
columnMapObj[j] = []
}
if(columnMapObj[j].includes(item)){
return false;
}
columnMapObj[j].push(item);
//验证3 * 3数组
let th = (i/3 | 0)+""+(j/3 | 0);
if(!squareMapObj[th]){
squareMapObj[th] = [];
}
if(squareMapObj[th].includes(item)){
return false;
}
squareMapObj[th].push(item)
}
}
return true;
};
看了其他道友提交后总结的
var isValidSudoku = function(board) {
let rowMapObj = Array(9)
.fill(0)
.map(() => ({})),
columnMapObj = Array(9)
.fill(0)
.map(() => ({})),
squareMapObj = Array(9)
.fill(0)
.map(() => ({}));
for(let i=0;i<9;i++){
for(let j=0;j<9;j++){
let item = board[i][j];
if(item !== "."){
let squareIndex = (j/3 | 0) + (i/3|0)*3;
if(squareMapObj[squareIndex][item] || rowMapObj[i][item] || columnMapObj[j][item] ){
return false;
}
squareMapObj[squareIndex][item] = rowMapObj[i][item] = columnMapObj[j][item] = true;
}
}
}
return true;
}
问题1:
如下写法麻烦吗?
let rowMapObj = Array(9)
.fill(0)
.map(() => ({}))
问题2:
第二种解法在验证3*3宫内有无重复时,是映射为0-9的key,第一种解法是映射为"00"-"22"这样的key值,最核心的地方在于什么?还有其他映射方式吗?
我一开始也想映射为0-9这种,没想出来。
问题3:
能将 rowMapObj、columnMapObj 、squareMapObj 合并成一种数据结构吗?
问题4
第二种解法的let squareIndex = (j/3 | 0) + (i/3|0)*3;
为什么不是 let squareIndex = (i/3 | 0) + (j/3|0)*3;
网友评论