题目描述:
Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
- Each row must contain the digits
1-9
without repetition. - Each column must contain the digits
1-9
without repetition. - Each of the 9
3x3
sub-boxes of the grid must contain the digits1-9
without repetition.
A partially filled sudoku which is valid.
The Sudoku board could be partially filled, where empty cells are filled with the character '.'
.
Example 1:
Input: [ ["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"] ] Output: true
Example 2:
Input: [ ["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"] ] Output: false Explanation: Same as Example 1, except with the 5 in the top left corner being modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid.
中文理解:
给定一个9*9的矩阵,矩阵的元素有1-9的数组和.组成,要求每一行的数字不能重复,每一列的数字不能重复,9*9的9个3*3的矩阵中1-9的数字也不能重复,如果满足条件返回true,否则返回false。
解题思路:
使用一个int[10]的数组来存储1-9的数字是否出现以及出现的次数,然后先横向遍历,判断每行是否满足条件,再纵向遍历,判断每列是否满足条件,再9个3*3小矩阵遍历,判断每个小矩阵是否满足条件,如果都满足则返回true,否则返回false。
代码(java):
class Solution {
public boolean isValidSudoku(char[][] board) {
int []numbers=new int[10];
for(int i=0;i<board.length;i++){
numbers=new int[10];
for(int j=0;j<board[0].length;j++){
if(board[i][j]>'0' && board[i][j]<='9')
numbers[board[i][j]-'0']++;
}
if(!number(numbers))return false;
}
for(int i=0;i<board[0].length;i++){
numbers=new int[10];
for(int j=0;j<board.length;j++){
if(board[j][i]>'0'&&board[j][i]<='9')
numbers[board[j][i]-'0']++;
}
if(!number(numbers))return false;
}
for(int i=0;i<board.length-2;i+=3){
for(int j=0;j<board[0].length-2;j+=3){
numbers=new int[10];
for(int k=0;k<=2;k++){
for(int l=0;l<=2;l++){
if(board[i+k][j+l]>'0'&&board[i+k][j+l]<='9')
numbers[board[i+k][j+l]-'0']++;
}
}
if(!number(numbers))return false;
}
}
return true;
}
public boolean number(int[]number){
for(int val:number){
if(val>1)return false;
}
return true;
}
}