【LeetCode 36】有效的数独

网友投稿 528 2022-10-31

【LeetCode 36】有效的数独

【LeetCode 36】有效的数独

题目描述

判断一个 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

示例 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-9 和字符 ‘.’ 。给定数独永远是 9x9 形式的。

解题思路

这个题目中,我们可以使用map来存贮已经遍历的过得值,如果map已经存在就说明不符合要求,不存在就将当前的值存入map,继续遍历。

首先,先对整个表格行和进行验证,最后在对九个小方格进行验证。需要注意的是,在对整个表格验证时,每次遍历完一行和一列,都要对map进行清空,在对九个小方格进行验证时,每遍历完一个小方格就需要对map进行清空。

这里我们用到了map数据结构的​​clear()​​​方法、​​has()​​​方法、​​set()​​方法,分别用来清空map,判断map中是否存在某值,在map中设置某值。

代码实现

/** * @param {character[][]} board * @return {boolean} */var isValidSudoku = function(board) { // 验证整个宫格的行和列 const mapRow = new Map(), mapCol = new Map() for(let i = 0; i < 9; i++){ mapRow.clear() mapCol.clear() for(let j = 0; j < 9; j++){ if(mapRow.has(board[i][j])) return false if(mapCol.has(board[j][i])) return false if(board[i][j] !== "."){ mapRow.set(board[i][j], j) } if(board[j][i] !== "."){ mapCol.set(board[j][i], i) } } } // 分别验证九个小个方格 const map = new Map() let m = 0, n = 0 while(m < 9){ while(n < 9){ map.clear() for(let i = m; i < m + 3; i++){ for(let j = n; j < n + 3; j++){ if(map.has(board[i][j])) return false if(board[i][j] !== "."){ map.set(board[i][j], j) } } } n += 3 } m += 3 n = 0 } return true};

提交结果

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:【LeetCode 67】二进制求和
下一篇:高度模块化, 遵循 KISS原则的区块链开发框架
相关文章

 发表评论

暂时没有评论,来抢沙发吧~