所以我的代码有点问题。.假设交叉检查行和列是否为相同的整数。
这是我到目前为止所拥有的..但是当我运行它时,它似乎只检查第一个整数。 (例如,数独板的第一行显示为1 2 2 2 2 2 2 2 2 2 2)它不会检测到明显的倍数2,但是如果我将输入更改为1 1 2 2 2 2 2 2 2 2,错误就会来临在这种情况下最多为1。多个建议来调整我的循环以使其遍历各列?
public static void validate(final int[][] sudokuBoard) {
int width = sudokuBoard[0].length;
int depth = sudokuBoard.length;
for (int i = 0; i < width; i++) {
int j = i;
int reference = sudokuBoard[i][j];
while (true) {
if ((j >= width) || (j >= depth)) {
break;
}
else if (i == j){
// do nothing
}
else if (j < width) {
int current = sudokuBoard[i][j];
if (current == reference) {
System.out.print("Invalid entry found (width)" + "\n");
System.out.print(current + "\n");
// invalid entry found do something
}
} else if (j < depth) {
// note reversed indexes
int current = sudokuBoard[j][i];
if (current == reference) {
System.out.print("Invalid entry found (depth)" + "\n");
System.out.print(current + "\n");
// invalid entry found do something
}
}
j++;
}
最佳答案
您的代码比应该的要复杂。当您可以拆分成几个不同的函数时,为什么将所有内容都放在一个函数中?
public static void Validate(final int[][] sudokuBoard)
{
int width = sudokuBoard[0].length;
int depth = sudokuBoard.length;
for(int i = 0; i < width; i++)
if(!IsValidRow(sudokuBoard, i, width))
{
//Do something - The row has repetitions
}
for(int j = 0; j < height; j++)
if(!IsValidColumn(sudokuBoard, j, width))
{
//Do something - The columns has repetitions
}
}
static bool IsValidRow(int[][] sudokuBoard, int referenceRow, int width)
{
//Compare each value in the row to each other
for(int i = 0; i < width; i++)
{
for(int j = i + 1; j < width; j++)
{
if(sudokuBoard[referenceRow][i] == sudokuBoard[referenceRow][j])
return false
}
}
return true;
}
static bool IsValidColumn(int[][] sudokuBoard, int referenceColumn, int height)
{
//Compare each value in the column to each other
for(int i = 0; i < height; i++)
{
for(int j = i + 1; j < height; j++)
{
if(sudokuBoard[i][referenceColumn] == sudokuBoard[j][referenceColumn])
return false
}
}
return true;
}
这样,您的代码将更易于维护/阅读。上面的代码尚未经过测试,但应该正确。
我建议逐步调试此代码,以真正了解发生的情况(如果您不清楚)。
关于java - Sudoku Checker 2D数组Java,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9316365/