请你判断一个 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
方法一:一次遍历
有效的数独满足以下三个条件:
同一个数字在每一行只能出现一次;
同一个数字在每一列只能出现一次;
同一个数字在每一个小九宫格只能出现一次。
可以使用哈希表记录每一行、每一列和每一个小九宫格中,每个数字出现的次数。只需要遍历数独一次,在遍历的过程中更新哈希表中的计数,并判断是否满足有效的数独的条件即可。
class Solution{
public boolean isValidSudoku(char[][] board){
int[][] rows=new int[9][9];
int[][] colummns=new int[9][9];
int[][][] subboxes=new int[3][3][9];
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
char c=board[i][j];
if(c!='.'){
int index=c-'0'-1;
rows[i][index]++;
columns[j][index]++;
subboxes[i/3][j/3][index]++;
if(rows[i][index]>1 || columns[][]>1 || subboxes[i/3][j/3][index]>1){
return false;
}
}
}
}
return true;
}
}
class Solution{
public boolean isValidSudoku(char[][] board){
for(int i=0;i<board.length;i++){
for(int j=0;j<board[0].length;j++){
if(board[i][j]>='0' && board[i][j]<='9'){
if(!getEffective(i,j,board)){
return false;
}
}
}
}
return true;
}
public boolean getEffective(int i,int j,char[][] board){
//验证一行
for(int k=0;k<board[i].length;i++){
if(board[i][k]==boardd[i][j] && k!=j){
return false;
}
}
//验证一列
for(int k=0;k<board.length;k++){
if(board[k][j]==board[i][j] && k!=i){
return false;
}
}
//验证当前3*3数组
int heng=(i/3)*3;
int zhong=(j/3)*3;
for(int k1=heng;k1<heng+3;k1++){
for(int k2=zhong;k2<zhong+3;k2++){
if((board[k1][k2]==board[i][j]) && (k1!=i && k2!=j)){
return false;
}
}
}
return true;
}
}