这题的解法是brute force,复杂度是O(81 + 81)。。。判断每一行每一列的代码我的想法跟code ganker的一致:用一个数组表示map;难点是判断每个unit是否valid,这种数组下标确实很难思考。。需要在纸上模拟一下才能看懂。
public boolean isValidSudoku(char[][] board) {
if (board.length != 9 || board[0].length != 9) return false;
int[] temp = new int[9];
//判断每一行
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] != '.') {
if (temp[board[i][j] - '1'] != 0) {
return false;
}
temp[board[i][j] - '1'] = 1;
}
}
temp = new int[9];
}
//判断每一列
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[j][i] != '.') {
if (temp[board[j][i] - '1'] != 0) {
return false;
}
temp[board[j][i] - '1'] = 1;
}
}
temp = new int[9];
}
//判断9个小units
for (int block = 0; block < 9; block++) {
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 (temp[board[i][j] - '1'] != 0) {
return false;
}
temp[board[i][j] - '1'] = 1;
}
}
}
temp = new int[9];
}
return true;
}
然后看了solutions里的解法,有个人用hashset,然后用了i j的reuse,很简洁,复杂度也稍低一些:
public boolean isValidSudoku(char[][] board) {
for(int i = 0; i<9; i++){
HashSet<Character> rows = new HashSet<Character>();
HashSet<Character> columns = new HashSet<Character>();
HashSet<Character> cube = new HashSet<Character>();
for (int j = 0; j < 9;j++){
if(board[i][j]!='.' && !rows.add(board[i][j]))
return false;
if(board[j][i]!='.' && !columns.add(board[j][i]))
return false;
int RowIndex = 3*(i/3);
int ColIndex = 3*(i%3);
if(board[RowIndex + j/3][ColIndex + j%3]!='.' && !cube.add(board[RowIndex + j/3][ColIndex + j%3]))
return false;
}
}
return true;
}