一、原题
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.
一、中文
验证一个数独棋盘是否合法,数独棋盘的验证规则见链接对应的页面。
数独棋盘是部分填满的,空的位置使用点来代替。
注意:合法的棋盘不一定要求的可解的,只要填充的数字满足要求就可以。
三、举例
每一行或者每一列的数字都必须是1--9内不重复的数字,随机找到一个3*3的矩阵也是1--9内不重复的数字的
四、思路
这个没有特别好的办法,行和列的话只能是逐行逐列地进行验证,3*3矩阵的验证倒是没有什么问题,关键点事如何寻找我们的3*3的矩阵,这样是比较有技巧的,我也是参考大神的方法。
五、程序
package code;
public class LeetCode25{
public static void main(String args[]){
int nums[][] = new int[][]{
{1, 3, 6, 5, 4, 7, 8, 2, 9},
{9, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 5, 0, 0, 0, 0, 0, 0},
{0, 0, 7, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 7, 0, 0, 6, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 1, 0, 0, 0, 9, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0}};
boolean res = checkAllMatrix(nums);
System.out.println("Res = "+res);
}
//检查9*9的矩阵是否是合法的
public static boolean checkAllMatrix(int[][]num){
int lineNum = num.length;
int rowNum = num[0].length;
//System.out.println(lineNum);
//System.out.println(rowNum);
//将矩阵进行按行进行遍历
for(int i = 0; i < lineNum; i++){
//lineTemp是存储一行元素的的临时矩阵
int lineTemp[] = new int[rowNum];
int rowTemp[] = new int[lineNum];
for(int j = 0; j < rowNum; j++){
lineTemp[j] = num[i][j];
rowTemp[j] = num[j][i];
//打印所有的元素
//System.out.print(lineTemp[j]+" ");
}
//下面对其每行或者每一列进行判断,只要有一个是false就返回false
if(!checkLineAndRow(lineTemp) || !checkLineAndRow(rowTemp)){
return false;
}
}
//用来存存储3*3临时矩阵
int numArray[] = new int[9];
int aryCount = 0;
//前两行是限定3*3的矩阵
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
//后面这两行是关键,让3*3矩阵在9*9的矩阵上不断的移动
for (int k = i * 3; k < (i + 1) * 3; k++) {
for (int l = j * 3; l < (j + 1) * 3; l++) {
numArray[aryCount] = num[k][l];
aryCount++;
if(aryCount == 9){
aryCount = 0;
}
}
}
if(!checkLineAndRow(numArray)){
return false;
}
}
}
return true;
}
//检查行和列的合法性
public static boolean checkLineAndRow(int num[]){
//tmp用来临时存储各个数的个数
int tmp[] = new int[num.length];
if(num == null || num.length < 1){
return false;
}else{
for(int i = 0; i < num.length; i++){
if(num[i] != 0){
tmp[num[i]-1] += 1;
}
}
//遍历存储个数的数组
for(int j = 0; j < tmp.length; j++){
if(tmp[j] > 1){
return false;
}
}
}
return true;
}
//检查3*3矩阵的合法性,这个方法暂时没有用到
public static boolean checkMatrix(int num[][]){
int lineNum = num.length;
int rowNum = num[0].length;
//临时进行存心的数组
int []tempAry = new int[lineNum * rowNum];
int k = 0;
//将二维数组转化成一维数组
for(int i = 0; i < lineNum; i++){
for(int j = 0; j < rowNum; j++){
tempAry[k] = num[i][j];
}
}
return checkLineAndRow(tempAry);
}
}