36. 有效的数独
Posted 落禅
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了36. 有效的数独相关的知识,希望对你有一定的参考价值。
36. 有效的数独
请你判断一个 9x9 的数独是否有效。只需要 根据以下规则 ,验证已经填入的数字是否有效即可。
数字 1-9 在每一行只能出现一次。
数字 1-9 在每一列只能出现一次。
数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。(请参考示例图)
数独部分空格内已填入了数字,空白格用 ‘.’ 表示。注意:
一个有效的数独(部分已被填充)不一定是可解的。
只需要根据以上规则,验证已经填入的数字是否有效即可。
输入: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 存在, 因此这个数独是无效的。
思路:这道题是判断这个数独是否有效,而题目已经告诉我们这是一个9x9的数独,那么我们只需要判断这个9x9的数独每一行,每一列这个数字是否只出来了一次,然后再判将9x9的数独分成9个3x3的小数独,判断这个3x3的格子里面每个数字是否只出现了一次,如果在每一行,每一列,每一个3x3的方格中每个数字都只出现了一次,那么就是有效的数独,反之就是无效的数独,那么这道题目的关键就变为:
1.该数字只在改行出现一次
2.该数字只在该列出现一次
3.该数字在各个3x3的放个里也只出现了一次
class Solution
public:
//最粗暴的方法:循环遍历每一个字符,判断他在这一行是否只出现一次,在这里列只出现一次,在周围3*3的宫格内只出现了一次
bool isValidSudoku(vector<vector<char>>& board)
//1.判断每个数字在改行只出现了一次
for(int i=0;i<9;i++)
//定义一个一维数组,采用哈希的思想,将这一行映射到这个数组中去
int row[9]=0;
for(int j=0;j<9;j++)
//如果不是数字进入下一层循环
if(board[i][j]=='.')
continue;
//如果(row[board[i][j]-'1']!=0,说明这个数已经在前面出现过一次了,直接返回false
if(row[board[i][j]-'1']!=0)
return false;
row[board[i][j]-'1']=1;
//2.判断每个数字在该列只出现了一次
for(int i=0;i<9;i++)
int col[9]=0;
for(int j=0;j<9;j++)
if(board[j][i]=='.')
continue;
if(col[board[j][i]-'1']!=0)
return false;
col[board[j][i]-'1']=1;
//3.判断每个数字在该3x3的格子里也只出现了一次
//将9x9的数独分割成9个3x3的小格子,然后像上面一样判断在这个格子里每个数字是否只出现了一次
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
int check[9]=0;
for(int ii=i*3;ii<i*3+3;ii++)
for(int jj=j*3;jj<j*3+3;jj++)
if(board[ii][jj]=='.')
continue;
if(check[board[ii][jj]-'1']!=0)
return false;
check[board[ii][jj]-'1']=1;
return true;
;
ps:由于上述循环都是常数级别的,因此时间复杂度为O(1)
感谢大家的观看,期待大家的评论,点赞,收藏,我们下次再见! To Be Continued…
以上是关于36. 有效的数独的主要内容,如果未能解决你的问题,请参考以下文章