Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
The Sudoku board could be partially filled, where empty cells are filled with the character '.'
.
A partially filled sudoku which is valid.
Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
题目:给一个数独表,判断现在是否符合数独的要求。行、列、粗线9宫格都包含1~9。即没有重复的数字。
思路:最简单的就是行、列、9宫格单独判断。
public boolean isValidSudoku(char[][] board) {
for(int i = 0; i < 9;i++) {
int[] num = new int[9];
int[] num1 = new int[9];
for(int j = 0; j < 9;j++) {//判断列
if(board[i][j] != '.') {
num[j] = board[i][j] -'0';
}
}
if(!isValid(num)) {
return false;
}
for(int k = 0; k < 9;k++) {//判断行
if(board[k][i] != '.') {
num1[k] = board[k][i] -'0';
}
}
if(!isValid(num1)) {
return false;
}
}
for(int i = 0; i < 9;i = i+3) {//判断9宫格
for(int y = 0; y < 9;y = y + 3) {
List<Integer> list = new ArrayList<Integer>();
for(int x = i;x < i+3 ;x++) {
for(int z = y;z < y+3;z++) {
if(board[x][z] != '.') {
if(!list.contains(board[x][z] - '0'))
list.add(board[x][z] - '0');
else {
return false;
}
}
}
}
}
}
return true;
}
public boolean isValid(int[] num) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
List<Integer> list = new ArrayList<Integer>();
for(int i = 0; i < num.length;i++) {
if(num[i] != 0 && list.contains(num[i])) {
return false;
} else {
list.add(num[i]);
}
}
return true;
}