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.
这道题的解法其实就是逐行逐列逐块检查逐块检查的时候,注意每一行的变换。行为/3*3~/3*3+3, 列为%3*3~%3*3+3
第1块的 行:0~3 列:0~3
第2块的 行:0~3 列:4~6
第3块的 行:0~3 列:7~9
第4块的 行:4~6 列:0~3
。。。
第9块的 行:7~9 列:7~9
代码如下 参考Code_Ganker
public boolean isValidSudoku(char[][] board) {
if (board == null || board.length != 9 || board[0].length != 9)
return false;
for (int i = 0; i < 9; i++) {
boolean[] table = new boolean[9];
for (int j = 0; j < 9; j++) {
if (board[i][j] != '.') {
if (table[(int) board[i][j] - '1'])
return false;
table[(int) board[i][j] - '1'] = true;
}
}
}
for (int j = 0; j < 9; j++) {
boolean[] table = new boolean[9];
for (int i = 0; i < 9; i++) {
if (board[i][j] != '.') {
if (table[(int) board[i][j] - '1'])
return false;
table[(int) board[i][j] - '1'] = true;
}
}
}
for (int block = 0; block < 9; block++) {
boolean[] table = new boolean[9];
for (int i = block / 3 * 3; i < block / 3 * 3 + 3; i++) {
for (int j = block % 3 * 3; j < block % 3 * 3 + 3; j++) {
if (board[i][j] != '.') {
if (table[(int) (board[i][j] - '1')]) {
return false;
}
table[(int) (board[i][j] - '1')] = true;
}
}
}
}
return true;
}