我正在用Java执行此Sudoku求解程序,由于某种原因,我的代码中有一个我无法修复的错误。我的代码有一个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();
}
最佳答案
在遇到错误的位置之前打印box_size
会发现实际上是0
。您永远不会在此构造函数中对其进行初始化,因此它将保留其默认值0
:
public SudokuSolver(int[][] board) {
this.board = board;
}
您可能打算包括
this.box_size = board.length / 3
这样的行。P.S. 导致错误的实际行是
else if (board[r + (i % box_size)][c + (i / box_size)] == num)
您可能不应该用
box_size
代替问题中的预期内容。