题目:
请你判断一个 9x9 的数独是否有效。只需要 根据以下规则 ,验证已经填入的数字是否有效即可。
数字 1-9 在每一行只能出现一次。
数字 1-9 在每一列只能出现一次。
数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。(请参考示例图)
数独部分空格内已填入了数字,空白格用 ‘.’ 表示。
*
注意:
一个有效的数独(部分已被填充)不一定是可解的。
只需要根据以上规则,验证已经填入的数字是否有效即可。
*
示例1:
输入: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”]]
*
输出:true
*
示例2:
*
输入:board =
[[“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 存在, 因此这个数独是无效的。
没想到最暴力的方法竟然是最简单的。不过也就遍历一遍,不管怎样都要遍历一遍。也就没那么纠结了
我们可以用三个二维数组来进行表示三个条件。①每一行一个数字至多出现一次,②每一列一个数字至多出现一次,③每一9宫格里面一个数字至多出现一次。
唯一的难点在于每一个9宫格里面的数字至多出现一次的思考。对于(i,j)位置的元素 j / 3 + i / 3/*3代表的就是第几个9宫格。就比如(0,0)(0,1)(0,2) (1,0)(1,1)(1,2)(3,0)(3,1)(3,2)就表示的同一个九宫格。
三个二维数组第一个下标分别表示,第i行,第j列,第n个9宫格,第二个下标表示当前出现的数字,对应的值表示出现的次数。
class Solution {
public boolean isValidSudoku(char[][] board) {
int [][]row =new int[9][10];
int [][]col =new int[9][10];
int [][]box =new int[9][10];
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j]=='.'){
continue;
}
int index = board[i][j]-'0';
if (row[i][index]==1 || col[j][index]==1|| box[j/3 + (i/3) * 3][index]==1){
return false;
}
row[i][index]=1;
col[j][index]=1;
box[j/3 + (i/3) * 3][index]=1;
}
}
return true;
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-sudoku
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/Y_peak/article/details/120343010
内容来源于网络,如有侵权,请联系作者删除!