36. Effective Sudoku
Determine if a 9x9 Sudoku is valid. You only need to verify whether the entered numbers are valid according to the following rules.
The numbers 1-9 can only appear once per line.
The numbers 1-9 can only appear once in each column.
Numbers 1-9 can only appear once in each 3x3 house separated by thick solid lines.
The image above is a partially filled valid Sudoku.
Numbers have been filled in the blanks of the Sudoku part, and the blanks are represented by '.'.
class Solution {
public boolean isValidSudoku(char[][] board) {
//执行用时:2 ms, 在所有 Java 提交中击败了96.52%的用户
//内存消耗:39.4 MB, 在所有 Java 提交中击败了94.88%的用户
int[] m = new int[10];
int n = board.length;
//每行只出现一次
int num;
for(int i = 0;i < n;++i){
//赋初始值
for(int k = 0;k < 10;++k){
m[k] = 0;
}
for(int j = 0;j < n;++j){
if (Character.isDigit(board[i][j])){
// 判断是否是数字
num = (int)board[i][j] - (int)('0');
//System.out.println(num);
if(m[num] == 0)
m[num] = 1;
else
return false;
}
}
}
//每列只出现一次
for(int j = 0;j < n;++j){
//赋初始值
for(int k = 0;k < 10;++k){
m[k] = 0;
}
for(int i = 0;i < n;++i){
if (Character.isDigit(board[i][j])){
// 判断是否是数字
num = (int)board[i][j] - (int)('0');
//System.out.println(num);
if(m[num] == 0)
m[num] = 1;
else
return false;
}
}
}
//每一个以粗实线分隔的 3x3 宫内只能出现一次。
for(int i = 0;i < 7;i += 3){
for(int j = 0;j < 7; j += 3){
//赋初始值
for(int k = 0;k < 10;++k){
m[k] = 0;
}
for(int p = 0; p < 3;++p){
for(int q = 0; q < 3;++q){
if (Character.isDigit(board[i + p][j + q])){
// 判断是否是数字
num = (int)board[i + p][j + q] - (int)('0');
//System.out.println(num);
if(m[num] == 0)
m[num] = 1;
else
return false;
}
}
}
}
}
return true;
}
}