判断一个 9x9 的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可。
- 数字 1-9 在每一行只能出现一次。
- 数字 1-9 在每一列只能出现一次。
- 数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。
上图是一个部分填充的有效的数独。
数独部分空格内已填入了数字,空白格用 '.' 表示。示例 1:
输入:
[ ["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"]] 输出: true
看见这道题我觉得应该能做出来,因为我做过五子棋,也是自己研究的数组棋盘遍历,感觉差不多
然而,没想到,做出来就用了我小半个下午的时间,并且用的也是很笨的遍历办法…var isValidSudoku = function (board) { //横向遍历 for (let i = 0; i !== 9; i++) { let temp = board[i].filter(value => value !== "."); if (new Set(temp).size !== temp.length) { return false; } } //纵向遍历 for (let i = 0; i !== 9; i++) { let temp = board.map(value => value.filter((value, index) => index === i)).map(value => value[0]).filter(value => value !== "."); if (new Set(temp).size !== temp.length) { return false; } } //3x3宫格遍历 for (let i = 0; i < 9; i += 3) { //先分为3个9x3的 let temp = board.map(value => value.filter((value, index) => index >= i && index < i + 3)).filter(value => value !== "."); //再把9x3分成3个3x3 for (let j = 0; j < 9; j += 3) { //转为1维数组去重判断长度 let temp_3x3 = temp.filter((value, index) => index >= j && index < j + 3).join(",").split(",").filter(value => value !== "."); if (new Set(temp_3x3).size !== temp_3x3.length) { return false; } } } return true;};
方法是很笨的硬莽干