数独只要每个单元格所在行,列,子数组中没有与其没有冲突即数独合法
只需要遍历单元格(i ,j)的时候记录下第i行有了board[i][j],第j列有了board[i][j],第k个子数独有了board[i][j]
其中k=(i / 3) * 3 + j / 3
因为数字范围是1-9,所以可以用二维数组来存储遍历过的数字,其中board[i][j]-'1'为对应的相应下标
public class Test36 {
@Test
public void test() {
// 1 2 3
// 2 3 1
// . . .
char[][] board = new char[][]{{'1','2','3'},{'4','5','6'},{'.','.','.'}};
System.out.println(isValidSudoku(board));
}
public boolean isValidSudoku(char[][] board) {
//记录下行,列,每个子数独已经遍历过的数字,如果当前遍历的数组已存在相应的行,列,子数独中,说明数独是不合法的
//初始值,数组全部为0, row[i]表示第i行已经占有了的数字
//rows[i][j]==1 表示第i行已经有了数字j+1
int[][] rows = new int[board.length][board[0].length];
int[][] cols = new int[board.length][board[0].length];
int[][] sons = new int[board.length][board[0].length];
for(int i=0; i<board.length; i++) {
for(int j=0; j<board[0].length; j++) {
if(board[i][j]!='.') {
int k = (i / 3) * 3 + j / 3;
int index = board[i][j]-'1';
if(rows[i][index]!=0 || cols[j][index]!=0 || sons[k][index]!=0) {
return false;
}
rows[i][index] = 1;
cols[j][index] = 1;
sons[k][index] = 1;
}
}
}
return true;
}
}