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.
超暴力破解,颤抖吧 =,=,这个思路实在是拙计啊。。。
java code
public class Solution {
public boolean isValidSudoku(char[][] board) {
for(int i=0; i<9 ; i++) {
for(int j=0; j<8; j++) {
if(board[i][j] != '.') {
for(int k=j+1; k<9; k++) {
if(board[i][j] == board[i][k]) return false;
}
}
}
for(int l=0; l<8; l++) {
if(board[l][i] != '.') {
for(int m=l+1; m<9; m++) {
if(board[l][i] == board[m][i]) return false;
}
}
}
}
for(int i=0; i<3; i++) {
for(int j=0; j<3; j++) {
for(int k=0; k<3; k++) {
for(int l=0; l<3; l++) {
if(board[3*i+k][3*j+l] != '.') {
for(int left=3*k+l+1; left<9; left++) {
int p = left/3;
int q = left%3;
if(board[3*i+k][3*j+l] == board[3*i+p][3*j+q]) {
return false;
}
}
}
}
}
}
}
return true;
}
}
323ms
转换一下,利用一个数组标记某个数字是否出现过
public class Solution {
public boolean isValidSudoku(char[][] board) {
boolean[] record = new boolean[9];
for(int i = 0; i < 9; i++) {
for (int temp = 0; temp < record.length; temp++) {
record[temp] = false;
}
for(int j = 0; j < 9; j++) {
if(board[i][j] != '.') {
int pos = board[i][j] - '1';
if(record[pos]) return false;
record[pos] = true;
}
}
}
for(int i = 0; i < 9; i++) {
for (int temp = 0; temp < record.length; temp++) {
record[temp] = false;
}
for(int j = 0; j < 9; j++) {
if(board[j][i] != '.') {
int pos = board[j][i] - '1';
if(record[pos]) return false;
record[pos] = true;
}
}
}
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
for (int temp = 0; temp < record.length; temp++) {
record[temp] = false;
}
for(int m = 0; m < 3; m++) {
for(int n = 0; n < 3; n++) {
if(board[3*i+m][3*j+n] != '.') {
int pos = board[3*i+m][3*j+n] - '1';
if(record[pos]) return false;
record[pos] = true;
}
}
}
}
}
return true;
}
}
297ms 0.0