3

我在 Java 中做这个数独求解器,由于某种原因,我的代码中有一个错误,我无法修复。我的代码有一个guess函数,它可以在每个框中猜测 1-9 的数字,同时检查该数字是否已经写过。

错误在该行中:

 else if (board[r + (i % 3)][c + (i / 3)] == num)

由于某种原因我得到一个ArithmeticException(除以0)我不明白为什么。希望你能帮忙

我的代码:

public class SudokuSolver
{
final int size = 9;
private int box_size;

private int[][] board;

// Create an empty board
public SudokuSolver()
{
  board = new int[size][size];
  this.box_size = size / 3;

}

// initialize a given board
public SudokuSolver(int[][] board)
{
  this.board = board;
}

public void setCell(int num, int row, int col)
{
  board[row][col] = num;
}

public int getCell(int row, int col)
{
  return board[row][col];
}

private boolean check(int num, int row, int col)
{
  int r = (row / 3) * 3;
  int c = (col / 3) * 3;

  for (int i = 0; i < size; i++)
  {
     if (board[row][i] == num)
        return false;

     else if (board[i][col] == num)
        return false;

     else if (board[r + (i % box_size)][c + (i / box_size)] == num)
        return false;
  }
  return true;
  }

  public boolean guess(int row, int col)
  {
  int nextCol = (col + 1) % size;
  int nextRow = (nextCol == 0) ? row + 1 : row;

  try
  {
     if (board[row][col] != 0)
        return guess(nextRow, nextCol);
  }
  catch (ArrayIndexOutOfBoundsException e)
  {
     return true;
  }

  for (int i = 1; i <= size; i++)
  {
     if (check(i, row, col))
     {
        board[row][col] = i;
        if (guess(nextRow, nextCol))
        {
           return true;
        }
     }
  }
  board[row][col] = 0;
  return false;
  }

  public void printBoard()
  {
  for (int row = 0; row < size; row++)
  {
     for (int col = 0; col < size; col++)
     {
        System.out.print(board[row][col] + "  ");
     }
     System.out.println();
   }

  }



  public static void main(String[] args)
  {

  int[][] board = { { 0, 6, 0, 1, 0, 4, 0, 5, 0 },
        { 0, 0, 8, 3, 0, 5, 6, 0, 0 }, { 2, 0, 0, 0, 0, 0, 0, 0, 1 },
        { 8, 0, 0, 4, 0, 7, 0, 0, 6 }, { 0, 0, 6, 0, 0, 0, 3, 0, 0 },
        { 7, 0, 0, 9, 0, 1, 0, 0, 4 }, { 5, 0, 0, 0, 0, 0, 0, 0, 2 },
        { 0, 0, 7, 2, 0, 6, 9, 0, 0 }, { 0, 4, 0, 5, 0, 8, 0, 7, 0 } };

  SudokuSolver ss = new SudokuSolver(board);
  ss.printBoard();
  System.out.println();
  System.out.println();
  if(ss.guess(0, 0))
     ss.printBoard();


 }
4

1 回答 1

3

在遇到错误之前打印box_size将显示它实际上是0. 您永远不会在此构造函数中初始化它,因此它保留其默认值0

public SudokuSolver(int[][] board) {
    this.board = board;
}

您可能打算包含类似this.box_size = board.length / 3.


PS导致错误的真正行是

else if (board[r + (i % box_size)][c + (i / box_size)] == num)

您可能不应该box_size在您的问题中替换您期望的内容。

于 2012-11-21T18:06:23.003 回答