這題的解法是brute force啥酱,復雜度是O(81 + 81)挡爵。姆泻。。判斷每一行每一列的代碼我的想法跟code ganker的一致:用一個數(shù)組表示map硼补;難點是判斷每個unit是否valid驮肉,這種數(shù)組下標確實很難思考。括勺。需要在紙上模擬一下才能看懂缆八。
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;
}