【问题标题】:Backtracking - Generate Sudokuarray回溯 - 生成数独数组
【发布时间】:2018-01-14 22:08:36
【问题描述】:

我想使用回溯生成一个简单的数独生成器。我被卡住了/不知道我是否正确使用了回溯。如果数字 zahl 有效(如果 zahl 在行/列或 9 个框之一中出现一次),则返回 zahlIstGueltigAufPosition

public static boolean fuelleArray(int y, int x, int zahl){

    sudokuArray[y][x]=zahl;


    if(zahlIstGueltigAufPosition(y,x,zahl)){

        if(x==8 && y<=7 && fuelleArray(y+1,0,1)){
            return true;

        }else if(x==8 && y==8 && fuelleArray(y,x,zahl)) {
            return true;

        }else if(x<=7 && y<=8){
            if(fuelleArray(y,x+1,1)) {
                return true;
            }
       }
    }else{
        if(zahl<9 && x<=8 && y<=8 ){fuelleArray(y,x,zahl+1);}
    }

    return false;
}

程序给出:

 1 2 3 4 5 6 7 8 9
 4 5 6 1 2 3 9 0 0
 0 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0 0

感谢您的帮助

【问题讨论】:

  • 首先,请格式化您的代码。在没有空格的情况下,我无法阅读它。其次,你没有告诉我们这段代码有什么问题。请edit您的问题提供此信息。
  • 请编辑您的问题以包含specific programming problem
  • 抱歉,更新了

标签: java recursion backtracking sudoku generate


【解决方案1】:

所以这是我的解决方案,有更好的方法可以使用回溯来生成数独,比如调用 fuelleArray(fieldIndex, numberInField)。 这样,回溯在代码中将更加明显和清晰,并且您不必像我一样处理连续结束的情况。

public static boolean fuelleArray(int y, int x, int zahl){

    sudokuArray[y][x]=zahl;

    if(zahlIstGueltigAufPosition(y,x,zahl)){
                                       //#1
        if(x==8 && y<=7){              //if you aren't at the end
            if(fuelleArray(y+1,0,1)){  //look if the the next field
                return true;           //is correct
            }
                                       //#2
        }else if(x==8 && y==8){        //if I am at the end 
            return true;               //return true, cause at 
                                       //zahlIstGueltigAufPosition
                                       //we know its correctly plassed               
                                       //by the SudokuRules


        }else if(x<=7 && y<=8){        //Just like #1, but there it
            if(fuelleArray(y,x+1,1)){  //was to handle the end of a 
                return true;           //row

            }
        }
    }

    if(zahl<9 && x<=8 && y<=8 ){      //if we are not correct we
        if(fuelleArray(y,x,zahl+1)){  //increase the number in that
            return true;              //field

        }
    }else {                           //if we are at number 9 we put 
        sudokuArray[y][x]=0;          //put it back to zero
                                      //
    }                                 //
    return false;                     //and return false

}

【讨论】:

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