0

我正在构建一个数独检查器,并且我已经制作了一个行检查器和一个列检查器。我目前正在尝试制作一个块检查器(3x3 块)。对此的任何见解都会很棒。

public boolean checkBlock (int col0to2, int row0to2)
 {
   int [] tempArray = new int [3];
   for (int x=0; x<3; x++)
   {
     for (int y=0; y<3;y++)
      {
        if ((board [col0to2+x][row0to2+y]) > 0 && (board [col0to2+x][row0to2+y]) < 10)
        {
          int tempVal = board [col0to2+x][row0to2+y];
          tempArray [tempVal - 1] = tempVal; // i think this line is giving me the run 
                                            // error   
    }
  } 
}
 return true;
}
4

4 回答 4

1
if ((board [col0to2+x][row0to2+y]) > 0 && (board [col0to2+x][row0to2+y]) < 10) {
      int tempVal = board [col0to2+x][row0to2+y];
      tempArray [tempVal - 1] = tempVal; // i think this line is giving me the run error

}

您对 tempval 的边界检查是它应该是 1 到 9(含)。假设它是 9。那么你分配 tempArray[8] = 9。你遇到了一个问题,因为 tempArray 被初始化为一个包含 3 个元素的数组。

我想你想要这样的东西:

tempArray = new int[9]

和任务是

tempArray[x*3 + y] = tempVal;

虽然我没有对此进行测试,但基本上它会用它找到的每个数字填充数组。

于 2013-04-24T20:58:45.540 回答
0

由于您需要处理数字 1-9,因此您需要 9 个整数的空间tempArray,但您声明它只有 3 个长。此外,您并没有真正检查是否使用了所有数字(并且没有重复)。

public boolean checkBlock (int col0to2, int row0to2) {
   int [] tempArray = new int [9];
   for (int x=0; x<3; x++) {
      for (int y=0; y<3;y++) {
         int tempVal = board [col0to2+x][row0to2+y];
         if (tempVal > 0 && tempVal < 10) {
            if (tempArray[tempVal - 1] != 0) {
               return false;
            }
            tempArray [tempVal - 1] = tempVal;
         }
      } 
   }
   return true;
}
于 2013-04-24T20:59:53.833 回答
0

有 9 个可能的值,所以你的数组应该是 size 9,而不是3

您只需要计算单元格是否已被填满。如果有,则返回 false。如果你在没有返回 false 的情况下完成它,则返回 true。

++使返回的值递增,以便您可以比较它。如果它是 2,那么单元格已经增加了。

代码:

public class BlockTest {
  public static boolean checkBlock (int col0to2, int row0to2)
  {
    int [] tempArray = new int[9];
    for (int x=0; x<3; x++)
    {
      for (int y=0; y<3;y++)
      {
        int tempVal = board [col0to2+x][row0to2+y];
        if (tempVal < 1 || tempVal > 9) return false;
        if (++tempArray[tempVal - 1] == 2) return false;
      } 
    }
    return true;
  }

  public static int[][] board = new int[9][9];
  public static void main(String[] args) {
    for(int i = 0; i < 3; i++) {
      for(int j = 0; j < 3; j++) {
        board[i][j] = i*3 + j + 1;
      }
    }
    System.out.println(checkBlock(0,0));
    board[0][0] = 7;
    System.out.println(checkBlock(0,0));
  }
}

输出:

true
false
于 2013-04-24T21:00:25.820 回答
0

我可以看到你来自哪里,但正如其他人所说,你的 tempArray 需要能够包含 9 个值。我之前写过一个数独检查器(uni assignment,解决方案检查是正确的,整个数独应用程序的分数超过了 90%),我的偏好是有一个包含 9 个值的数组,每个值代表 1-9 个数字,但我没有将值设置为 tempVal,而是增加了它。使检查您只得到每个数字中的一个变得更容易。

int [] boxCounts = {0, 0, 0, 0, 0, 0, 0, 0, 0};

// X loop
    // y loop
        // get value
        boxCounts[value - 1]++;
    // end y loop
// end x loop

// check we found one of each
for(int j = 0; j < 9; j++) {
    if(boxCounts[j] != 1 )
        return false;
    }
}
于 2013-04-24T21:17:02.667 回答