0

嗨,谁能告诉我我在这里做错了什么?我想检查每个子网格是否有 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;
}
}
4

1 回答 1

1

问题出在您的 isBoxValid() 方法中。您正在初始化r和分别ccurrentRowcurrentCol,但是您将循环运行到硬编码值 3,而不是3+currentRow3+currentCol。当 currentRow 和 currentCol 为 0 时,它可以正常工作,但对于其他数字,则不是那么多。

哦,编写简洁代码的另一个好处是:更容易看到错误在哪里。再看一下您硬编码的数字:您将列增加 3,将行增加 1。如果将其压缩成一对循环check(),那将更容易发现。for

于 2011-05-27T04:42:18.653 回答