DDR爱好者之家 Design By 杰米

本文实例讲述了JS实现判断有效的数独算法。分享给大家供大家参考,具体如下:

判断一个 9x9 的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可。

1.数字 1-9 在每一行只能出现一次。
2.数字 1-9 在每一列只能出现一次。
3.数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。

JS实现判断有效的数独算法示例

数独部分空格内已填入了数字,空白格用 ‘.' 表示。

示例 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

示例 2:

输入:

[
["8","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"]
]

输出: false

解释: 除了第一行的第一个数字从 5 改为 8 以外,空格内其他数字均与 示例1 相同。

但由于位于左上角的 3x3 宫内有两个 8 存在, 因此这个数独是无效的。

说明:

1.一个有效的数独(部分已被填充)不一定是可解的。
2.只需要根据以上规则,验证已经填入的数字是否有效即可。
3.给定数独序列只包含数字 1-9 和字符 ‘.' 。
4.给定数独永远是 9x9 形式的。

<script>
var isValidSudoku = function(board) {
 const boxes = [{}, {}, {}, {}, {}, {}, {}, {}, {}];
 const cols = [{}, {}, {}, {}, {}, {}, {}, {}, {}];
 const rows = [{}, {}, {}, {}, {}, {}, {}, {}, {}];
 let test = [{}, {}, {}, {}, {}, {}, {}, {}, {}];
 for (let i = 0; i < 9; i++) {
  for (let j = 0; j < 9; j++) {
   const digit = board[i][j];
   if (digit !== '.') {
    const k = Math.floor(j / 3) + (Math.floor(i / 3) * 3);
    if (boxes[k][digit] || cols[j][digit] || rows[i][digit]) {
     return false;
    }
    boxes[k][digit] = cols[j][digit] = rows[i][digit] = true;
   }
  }
 }
 return true;
};
const board = [
 ["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"]
]
console.log(isValidSudoku(board))
</script>

使用在线HTML/CSS/JavaScript代码运行工具:http://tools.jb51.net/code/HtmlJsRun测试上述代码,可得如下运行结果:

JS实现判断有效的数独算法示例

更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《JavaScript数学运算用法总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript数组操作技巧总结》、《JavaScript排序算法总结》、《JavaScript遍历算法与技巧总结》、《JavaScript查找算法技巧总结》及《JavaScript错误与调试技巧总结》

希望本文所述对大家JavaScript程序设计有所帮助。

DDR爱好者之家 Design By 杰米
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
DDR爱好者之家 Design By 杰米