数独生成器:递归不起作用

Sudoku generator: Recursion not working

我想要完成的事情:

while(there are empty squares)
   get a random number of the remaining numbers
   if(the number hasn't been tried before)
      if(it fits)
        place it and remove from available
        next square
   if(all numbers have been tried)
       forget it
       move back a square and try a different number

这个循环在 availableNumbers = 64 时停止,有时是 37,有时是 81 等等。是什么阻止了它一直进行下去?为什么有时卡住有时回溯?

while(availableNumbers.size()>0){
            rand = rn.nextInt(availableNumbers.size());
            number = availableNumbers.get(rand);
            if(number != triedNumbers[y][x][number-1]){    // If the number hasn't been tried in this square
                if(!checkConflict(number)){
                    squares[y][x].setText(""+number);
                    availableNumbers.remove(new Integer(number));
                    addedNumbers[y][x] = number;
                    triedNumbers[y][x][number-1] = number;
                    moveAhead();
                }
            }
            if(Arrays.equals(triedNumbers[y][x],refArray)){    // If all numbers have been tried in that square
                emptySquare();    // Forget all numbers tried in current square
                moveBack();
            }
}

emptySquare、moveBack、moveAhead 和 checkConflicts 都按预期工作(根据我的测试)。这是他们的要点:https://gist.github.com/WQvist/ac4296fb3a86fdc3d713

编辑:我终于解决了。感谢所有的帮助。看我的回答。

您的伪代码不正确。应该是:

while(there are empty squares)
   get a random number of the remaining numbers
   if(the number hasn't been tried before)
      if(it fits)
        place it and remove from available
        next square
   while(all numbers have been tried)
       forget it
       move back a square
   try a different number

有时您必须返回不止一个方格才能到达您尚未尝试所有数字的方格。

解决了!

while(currentSquare<81){
            rand = rn.nextInt(availableNumbers.size());
            number = availableNumbers.get(rand);
            if(square[currentSquare].contains(number)){
                square[currentSquare].remove(new Integer(number));
                if(!checkConflict(number)){
                    squares[y][x].setText(""+number);
                    addedNumbers[y][x] = number;
                    availableNumbers.remove(rand);
                    moveAhead();
                    currentSquare++;
                }
            }
            if(currentSquare < 81){
                while(square[currentSquare].isEmpty()){
                    square[currentSquare].addAll(refList);
                    addedNumbers[y][x] = 0;
                    availableNumbers.addAll(refList);
                    moveBack();
                    if(currentSquare>=1){
                        currentSquare--;
                    }
                }
            }
        }