You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

数独求解代码异常:返回true不终止运行且无正确结果

数独求解代码问题排查与修复

问题根源分析

你的代码存在两个核心问题,导致返回true时无法终止且不输出答案:

1. 递归调用未传递返回值

在sudokuSolver方法中,当当前单元格已有预设数字(值不为0)时,你调用了递归但没有返回递归的结果。这会导致程序继续执行后续的填数逻辑,覆盖已有数字,同时无法将递归的成功信号(true)向上传递,最终导致即使找到解也无法正确终止。

错误代码片段:

if (sudoku[row][col] != 0) {
    sudokuSolver(sudoku, nextRow, nextCol); // 未返回结果
}

2. 未触发结果打印

main方法中仅判断了解是否存在,但没有调用printSudoku方法输出求解后的数独数组,所以即使解存在也看不到具体答案。

修复后的代码

针对上述问题,修改如下:

修改sudokuSolver方法

public static boolean sudokuSolver(int sudoku[][], int row, int col) {
    // Base case
    if (row == 9) {
        return true;
    }

    // recursion
    int nextRow = row;
    int nextCol = col+1;

    if (col+1 == 9) {
        nextRow = row+1;
        nextCol = 0;
    }

    // check place value is zero or somethingelse
    if (sudoku[row][col] != 0) {
        // 关键:返回递归调用的结果
        return sudokuSolver(sudoku, nextRow, nextCol);
    }

    // placement of digit
    for (int digit = 1; digit <= 9; digit++) {
        if (isSafe(sudoku, row, col, digit)) {
            sudoku[row][col] = digit;
            if (sudokuSolver(sudoku, nextRow, nextCol)) {
                return true;
            }
            sudoku[row][col] = 0;
        }
    }

    return false;
}

修改main方法

在判断解存在后,调用printSudoku输出结果:

public static void main(String args[]) {
    int sudoku[][] = { { 0, 0, 8, 0, 0, 0, 0, 0, 0 },
            { 4, 9, 0, 1, 5, 7, 0, 0, 2 },
            { 0, 0, 3, 0, 0, 4, 1, 9, 0 },
            { 1, 8, 5, 0, 6, 0, 0, 2, 0 },
            { 0, 0, 0, 0, 2, 0, 0, 6, 0 },
            { 9, 6, 0, 4, 0, 5, 3, 0, 0 },
            { 0, 3, 0, 0, 7, 2, 0, 0, 4 },
            { 0, 4, 9, 0, 3, 0, 0, 5, 7 },
            { 8, 2, 7, 0, 0, 9, 0, 1, 3 }, };

    if (sudokuSolver(sudoku, 0, 0)) {
        System.out.println("Solution exist");
        printSudoku(sudoku); // 添加打印逻辑
    } else {
        System.out.println("Solution not exist");
    }
}

修复效果

修改后,程序会在找到解时正确终止,并打印出完整的数独答案;若无解则输出对应的提示信息,符合预期逻辑。

内容的提问来源于stack exchange,提问作者Kishan Verma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 18:04:56