嗨,谁能告诉我我在这里做错了什么? 我想检查 9×9 正方形中每个子网格的重复值。
我的方法首先通过为每个子网格创建一个一维数组来工作,然后可以检查每个子网格的每一行。为了让它到达每个子网格,我自己提供了它的坐标。 它检查第一个网格 0,0 但不检查其他子网格的重复值。
谁能告诉我我做错了什么?
public class SudokuPlayer
{
private int [][] game;
public enum CellState { EMPTY, FIXED, PLAYED };
private CellState[][] gamestate;
private int [][] copy;
private static final int GRID_SIZE=9;
private boolean whichGameToReset;
private int len;
private int stateSize;
private int row;
private int col;
private boolean coordinates(int startX, int startY)
{
row=startX;
col=startY;
if(isBoxValid()==false)
{
return false;
}
return true;
}
public boolean check()
{
if(coordinates(0,0)==false)
{
return false;
}
if(coordinates(0,3)==false)
{
return false;
}
if(coordinates(0,6)==false)
{
return false;
}
if(coordinates(1,0)==false)
{
return false;
}
if( coordinates(1,3)==false)
{
return false;
}
if( coordinates(1,6)==false)
{
return false;
}
if(coordinates(2,0)==false)
{
return false;
}
if(coordinates(2,3)==false)
{
return false;
}
if(coordinates(2,6)==false)
{
return false;
}
return true;
}
private boolean isBoxValid()
{
int[] arrayCopy = new int[game.length];
int currentRow = (row/3)*3;
int currentCol = (col/3)*3;
int i = 0;
for ( int r =currentRow; r < 3; r++)
{
for( int c =currentCol; c < 3; c++)
{
arrayCopy[i] = game[r][c];
i++;
}
}
for ( int p =0; p < arrayCopy.length; p++)
{
for ( int j = p+1; j < arrayCopy.length; j++)
{
if ( arrayCopy[p] == arrayCopy[j] && arrayCopy[j]!=0)
{
return false;
}
}
}
return true;
}
}
最佳答案
问题出在您的 isBoxValid() 方法中。您将 r
和 c
分别初始化为 currentRow
和 currentCol
,但运行循环直到硬编码值 3,而不是 3+currentRow
或 3+currentCol
。当 currentRow 和 currentCol 为 0 时,效果很好,但对于其他数字,效果就不那么好了。
哦,编写简洁代码的另一件事是:更容易看到错误所在。再看一下硬编码到 check()
中的数字:您将列增加 3,将行增加 1。如果将其压缩为一对 for
循环。
关于java - 数独检查子网格错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6147844/