判断一个 9x9 的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可。
数字 1-9 在每一行只能出现一次。
数字 1-9 在每一列只能出现一次。
数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。
上图是一个部分填充的有效的数独。
数独部分空格内已填入了数字,空白格用 ‘.’ 表示。
输入:
[
[“5”,”3”,”.”,”.”,”7”,”.”,”.”,”.”,”.”],
[“6”,”.”,”.”,”1”,”9”,”5”,”.”,”.”,”.”],
[“.”,”9”,”8”,”.”,”.”,”.”,”.”,”6”,”.”],
[“8”,”.”,”.”,”.”,”6”,”.”,”.”,”.”,”3”],
[“4”,”.”,”.”,”8”,”.”,”3”,”.”,”.”,”1”],
[“7”,”.”,”.”,”.”,”2”,”.”,”.”,”.”,”6”],
[“.”,”6”,”.”,”.”,”.”,”.”,”2”,”8”,”.”],
[“.”,”.”,”.”,”4”,”1”,”9”,”.”,”.”,”5”],
[“.”,”.”,”.”,”.”,”8”,”.”,”.”,”7”,”9”]
]
输出: true
输入:
[
[“8”,”3”,”.”,”.”,”7”,”.”,”.”,”.”,”.”],
[“6”,”.”,”.”,”1”,”9”,”5”,”.”,”.”,”.”],
[“.”,”9”,”8”,”.”,”.”,”.”,”.”,”6”,”.”],
[“8”,”.”,”.”,”.”,”6”,”.”,”.”,”.”,”3”],
[“4”,”.”,”.”,”8”,”.”,”3”,”.”,”.”,”1”],
[“7”,”.”,”.”,”.”,”2”,”.”,”.”,”.”,”6”],
[“.”,”6”,”.”,”.”,”.”,”.”,”2”,”8”,”.”],
[“.”,”.”,”.”,”4”,”1”,”9”,”.”,”.”,”5”],
[“.”,”.”,”.”,”.”,”8”,”.”,”.”,”7”,”9”]
]
解释: 除了第一行的第一个数字从 5 改为 8 以外,空格内其他数字均与 示例1 相同。
但由于位于左上角的 3x3 宫内有两个 8 存在, 因此这个数独是无效的。
一个有效的数独(部分已被填充)不一定是可解的。
只需要根据以上规则,验证已经填入的数字是否有效即可。
给定数独序列只包含数字 1-9 和字符 ‘.’ 。
给定数独永远是 9x9 形式的。
package leetCode;
/**
* 2018.7.20 有效的数独
* 笨办法,就一次判断每一列每一行和每个3x3的块
* @author dhc
*
*/
public class ThirtySix {
//判断一个长度为9的一位数组是否存在相等的元素
public static boolean judgeOneColOrRaw(char[] col) {
boolean flag = false;
out:for (int i = 0; i < col.length; i++) {
if(col[i] == '.') {
continue;
}
for (int j = i+1; j < col.length; j++) {
if(col[j] == '.') {
continue;
}
if(col[i] == col[j]) {
flag = true;
break out;
}
}
}
return flag;
}
//获取二维数组的一列
public static char[] getOneCol(char[][] b,int col) {
char[] re = new char[9];
for (int i = 0; i < b.length; i++) {
re[i] = b[i][col];
}
return re;
}
//获取二维数组的一行
public static char[] getOneRaw(char[][] b,int raw) {
char[] re = new char[9];
for(int i = 0;i < b.length;i++) {
re[i] = b[raw][i];
}
return re;
}
public static boolean isValidSudoku(char[][] board) {
boolean isValid = true;
//判断行或列
for (int i = 0; i < 9; i++) {
//取出第i行
char[] raw = getOneRaw(board,i);
//取出第i列
char[] col = getOneCol(board,i);
if(judgeOneColOrRaw(raw) || judgeOneColOrRaw(col)) {
isValid = false;
break;
}
}
//判断3x3的块
for(int i = 0;i < board.length;i = i + 3) {
for(int j = 0;j < board.length;j = j + 3) {
char[] tat = new char[9];
tat[0] = board[i][j];
tat[1] = board[i][j+1];
tat[2] = board[i][j+2];
tat[3] = board[i+1][j];
tat[4] = board[i+1][j+1];
tat[5] = board[i+1][j+2];
tat[6] = board[i+2][j];
tat[7] = board[i+2][j+1];
tat[8] = board[i+2][j+2];
if(judgeOneColOrRaw(tat)) {
isValid = false;
}
}
}
return isValid;
}
public static void main(String[] args) {
char[][] b = new char[][]{
{'8','3','.','.','7','.','.','.','.'},
{'8','3','.','.','7','.','.','.','.'},
{'8','3','.','.','7','.','.','.','.'},
{'8','3','.','.','7','.','.','.','.'},
{'8','3','.','.','7','.','.','.','.'},
{'8','3','.','.','7','.','.','.','.'},
{'8','3','.','.','7','.','.','.','.'},
{'8','3','.','.','7','.','.','.','.'},
{'8','3','.','.','7','.','.','.','.'},};
System.out.println(isValidSudoku(b));
}
}