gpt4 book ai didi

Java数组越界-数独

转载 作者:行者123 更新时间:2023-12-01 10:13:40 26 4
gpt4 key购买 nike

我的填充数独板的代码如下所示:

public class SudokuBoard {

static int N = 9;
static int[][] grid = new int[N][N];

static void printGrid()
{
for (int row = 0; row < N; row++)
{
for (int col = 0; col < N; col++) {
System.out.printf("%5d", grid[row][col]);
}
System.out.println("\n");
}
}

private static boolean checkRow(int row, int num)
{
for( int col = 0; col < 9; col++ )
if(grid[row][col] == num)
return false;

return true;
}

private static boolean checkCol(int col, int num)
{
for( int row = 0; row < 9; row++ )
if(grid[row][col] == num)
return false;

return true;
}

private static boolean checkBox(int row, int col, int num)
{
row = (row / 3) * 3;
col = (col / 3) * 3;

for(int r = 0; r < 3; r++)
for(int c = 0; c < 3; c++)
if(grid[row+r][col+c] == num)
return false;

return true;
}

public static boolean fillBoard(int row, int col, int[][] grid)
{
if(row==9)
{
col = 0;
if(col++ == 9)
return true;
}
if(grid[row][col] != 0)
return fillBoard(row+1, col, grid);
for(int num = 1; num <=9; num++)
{
if(checkRow(row,num) && checkCol(col,num) && checkBox(row,col,num)){
grid[row][col] = num;
if(fillBoard(row+1, col, grid))
return true;
}
}
grid[row][col] = 0;
return false;
}

static public void main(String[] args){
fillBoard(0, 0, grid);
printGrid();
}
}

它使用回溯算法来根据数独游戏规则检查数字的放置是否正确。它抛出错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
at SudokuBoard.fillBoard(SudokuBoard.java:68)
at SudokuBoard.fillBoard(SudokuBoard.java:74) x9
at SudokuBoard.main(SudokuBoard.java:84)

哪里出界了?我看不到...

最佳答案

该 block 看起来错误:

    if(row==9)
{
col = 0;
if(col++ == 9)
return true;
}

我怀疑你想要这个:

    if(row==9) {
row = 0;
if(++col == 9)
return true;
}

关于Java数组越界-数独,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36023906/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com