【问题标题】:Sudoku Backtracking数独回溯
【发布时间】:2015-04-03 00:17:56
【问题描述】:

以下是我的解决方法。当我在我的 main 方法中调用它时,什么都没有发生,所有后续它都没有执行,但 eclipse 没有报告错误。

    public boolean solve(int r, int c){
    if(c>8){
        c=0;
        r++;
    }
    if(r>8){
        return true;
    }
    while(table[r][c].value!=0){
        c++;
        if(c>8){
            c=-0;
            r++;
        }
        if(r>8){
            return true;
        }
    }
    for(int k=1;k<10;k++){
        if(table[r][c].checkRow(k)&&table[r][c].checkCol(k)&&table[r][c].checkCube(k)){
            table[r][c].value=k;
            solve(r,c);
        }
    }
    table[r][c].value=0;
    return false;
}

这个算法会回溯吗?如果不是,为什么?

【问题讨论】:

    标签: sudoku backtracking


    【解决方案1】:

    它看起来像一个逻辑错误,因此 eclipse 没有报告任何内容。

    在代码的 for 循环部分,你应该有这样的东西

     for(int k=1;k<10;k++){
            if(table[r][c].checkRow(k)&&table[r][c].checkCol(k)&&table[r][c].checkCube(k)){
                table[r][c].value=k;
                if(solve(r,c)){
                    return true;
                 }
                 table[r][c].value=0;
            }
        }
    

    在您的情况下,您在 for 循环之外取消分配表,这可以防止代码回溯。

    Here 是我解决数独的代码。希望能帮助到你。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多