Java 在具有有限资源(如堆栈)的机器上创建数独矩阵而不进行递归

Java 在具有有限资源(如堆栈)的机器上创建数独矩阵而不进行递归,java,algorithm,recursion,sudoku,Java,Algorithm,Recursion,Sudoku,我正在尝试为watch创建一个应用程序,我的内存资源非常有限,当我使用递归生成数独矩阵时,会出现堆栈溢出异常。如果我每次都想生成一个随机数独,但系统资源有限,没有递归,有人能给我任何输入吗。我目前正在使用下面的代码,它给出了堆栈溢出异常 package test; import java.util.*; import java.text.*; /** * The SudokuGenerator class creates a random standard (9x9) Sudoku boar

我正在尝试为watch创建一个应用程序,我的内存资源非常有限,当我使用递归生成数独矩阵时,会出现堆栈溢出异常。如果我每次都想生成一个随机数独,但系统资源有限,没有递归,有人能给我任何输入吗。我目前正在使用下面的代码,它给出了堆栈溢出异常

package test;

import java.util.*;
import java.text.*;

/**
* The SudokuGenerator class creates a random standard (9x9) Sudoku board
* through the use of backtracking techniques.
*/
public class validS {
public static final int BOARD_WIDTH = 9;
public static final int BOARD_HEIGHT = 9;

/**
 * Constructor. Resets board to zeros
 */
public validS() {
    board = new int[BOARD_WIDTH][BOARD_HEIGHT];
}

/**
 * Driver method for nextBoard.
 *
 * @param difficult
 *            the number of blank spaces to insert
 * @return board, a partially completed 9x9 Sudoku board
 */
public int[][] nextBoard(int difficulty) {
    board = new int[BOARD_WIDTH][BOARD_HEIGHT];
    nextCell(0, 0);
    makeHoles(difficulty);
    return board;

}

/**
 * Recursive method that attempts to place every number in a cell.
 *
 * @param x
 *            x value of the current cell
 * @param y
 *            y value of the current cell
 * @return true if the board completed legally, false if this cell has no
 *         legal solutions.
 */
public boolean nextCell(int x, int y) {
    int nextX = x;
    int nextY = y;
    int[] toCheck = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    Random r = new Random();
    int tmp = 0;
    int current = 0;
    int top = toCheck.length;

    for (int i = top - 1; i > 0; i--) {
        current = r.nextInt(i);
        tmp = toCheck[current];
        toCheck[current] = toCheck[i];
        toCheck[i] = tmp;
    }

    for (int i = 0; i < toCheck.length; i++) {
        if (legalMove(x, y, toCheck[i])) {
            board[x][y] = toCheck[i];
            if (x == 8) {
                if (y == 8)
                    return true;// We're done! Yay!
                else {
                    nextX = 0;
                    nextY = y + 1;
                }
            } else {
                nextX = x + 1;
            }
            if (nextCell(nextX, nextY))
                return true;
        }
    }
    board[x][y] = 0;
    return false;
}

/**
 * Given a cell's coordinates and a possible number for that cell, determine
 * if that number can be inserted into said cell legally.
 *
 * @param x
 *            x value of cell
 * @param y
 *            y value of cell
 * @param current
 *            The value to check in said cell.
 * @return True if current is legal, false otherwise.
 */
private boolean legalMove(int x, int y, int current) {
    for (int i = 0; i < 9; i++) {
        if (current == board[x][i])
            return false;
    }
    for (int i = 0; i < 9; i++) {
        if (current == board[i][y])
            return false;
    }
    int cornerX = 0;
    int cornerY = 0;
    if (x > 2)
        if (x > 5)
            cornerX = 6;
        else
            cornerX = 3;
    if (y > 2)
        if (y > 5)
            cornerY = 6;
        else
            cornerY = 3;
    for (int i = cornerX; i < 10 && i < cornerX + 3; i++)
        for (int j = cornerY; j < 10 && j < cornerY + 3; j++)
            if (current == board[i][j])
                return false;
    return true;
}

/**
 * Given a completed board, replace a given amount of cells with 0s (to
 * represent blanks)
 *
 * @param holesToMake
 *            How many 0s to put in the board.
 */
public void makeHoles(int holesToMake) {
    /*
     * We define difficulty as follows: Easy: 32+ clues (49 or fewer holes)
     * Medium: 27-31 clues (50-54 holes) Hard: 26 or fewer clues (54+ holes)
     * This is human difficulty, not algorighmically (though there is some
     * correlation)
     */
    double remainingSquares = 81;
    double remainingHoles = (double) holesToMake;

    for (int i = 0; i < 9; i++)
        for (int j = 0; j < 9; j++) {
            double holeChance = remainingHoles / remainingSquares;
            if (Math.random() <= holeChance) {
                board[i][j] = 0;
                remainingHoles--;
            }
            remainingSquares--;
        }
}

/**
 * Prints a representation of board on stdout
 */
public void print() {
    for (int i = 0; i < 9; i++) {
        for (int j = 0; j < 9; j++)
            System.out.print(board[i][j] + "  ");
        System.out.println();
    }
    System.out.println();
}

public static void main(String[] args) {
    validS sg = new validS();
    sg.nextBoard(70);
    sg.print();
}

int[][] board;
private int operations;
封装测试;
导入java.util.*;
导入java.text.*;
/**
*数独生成器类创建一个随机标准(9x9)数独板
*通过使用回溯技术。
*/
公共类有效期{
公共静态最终int板_宽度=9;
公共静态最终内板高度=9;
/**
*构造函数。将电路板重置为零
*/
公共validS(){
线路板=新的整数[线路板宽度][线路板高度];
}
/**
*下一个板的驱动程序方法。
*
*@param困难
*要插入的空格数
*@return board,部分完成的9x9数独板
*/
公共int[][]下一个板(int难度){
线路板=新的整数[线路板宽度][线路板高度];
nextCell(0,0);
制造漏洞(困难);
返回板;
}
/**
*尝试将每个数字放入单元格的递归方法。
*
*@param x
*当前单元格的x值
*@param y
*当前单元格的y值
*@return true如果棋盘合法完成,则返回true如果此单元格没有
*法律解决办法。
*/
公共布尔nextCell(整数x,整数y){
int-nextX=x;
int-nextY=y;
int[]toCheck={1,2,3,4,5,6,7,8,9};
随机r=新随机();
int-tmp=0;
int电流=0;
int top=toCheck.length;
对于(int i=top-1;i>0;i--){
电流=r.nextInt(i);
tmp=检查[当前];
toCheck[current]=toCheck[i];
toCheck[i]=tmp;
}
for(int i=0;i2)
如果(x>5)
角x=6;
其他的
角x=3;
如果(y>2)
如果(y>5)
y=6;
其他的
cornerY=3;
对于(int i=cornerX;i<10&&i如果(Math.random()您可能会耗尽堆栈空间,因为在“最坏”的情况下,即在完成构建板时,您有81次调用nextCell+1调用legalMove。我不是Java人士,但首先要尝试的是在nextCall开始时去掉变量:

--此随机对象可能在调用之间共享; 如果您需要使用nextX,nextY(实际上您没有)尝试在“if(legalMove(x,y,toCheck[i]){”块中使用它们; 不要使用top,只需使用toCheck.length初始化循环变量; 在“洗牌循环”中声明tmp。 在geral中,保持变量尽可能地局部是一个很好的实践,不仅仅是因为内存管理

如果这没有帮助(这是很有可能的),那么您可以尝试使用自己的控制结构——一个只包含xs、ys和tocheck的堆栈, 始终尝试堆栈中的第一个,直到检查完为止。下面是一个示例js实现(我包括了整个内容,以便您可以在浏览器中进行测试,但您只对buildBoard()的代码感兴趣):

var rand=function(uppBnd){return(Math.floor(Math.random()*uppBnd));};
var board=null;///仅用于作用域
函数mkEmptyBoard(h,w){///想不出在js中初始化hxw数组的其他方法
var b=[];
对于(i=0;i=5)
角x=6;
其他的
角x=3;
如果(y>2)
如果(y>5)
y=6;
其他的
cornerY=3;
对于(变量i=cornerX;i<10&&i0){
var ch=stck[0]。check.shift();
if(legalMove)(stck[0].x,stck[
int nextX = x;
int nextY = y;

Random r = new Random();
int tmp = 0;
int current = 0;
int top = toCheck.length;
var rand = function(uppBnd) { return(Math.floor(Math.random()*uppBnd)); };
var board = null; /// just for the scoping

function mkEmptyBoard(h,w) { /// can't think of other way to initialize hxw array in js
  var b=[];
  for(i=0;i<h;i++) {
    var r=[];
    for(j=0;j<w;j++) r.push(0);
    b.push(r);
  }
  return b;
}

/// this one is taken from your code, btw you can make this corner things easier.
function legalMove(x,y,current) {
  for (var i = 0; i < 9; i++) {
    if (current == board[x][i])
        return false;
  }
  for (var i = 0; i < 9; i++) {
    if (current == board[i][y])
        return false;
  }
  var cornerX = 0;
  var cornerY = 0;
  if (x > 2)
    if (x > 5)
      cornerX = 6;
    else
      cornerX = 3;
    if (y > 2)
    if (y > 5)
      cornerY = 6;
    else
      cornerY = 3;
  for (var i = cornerX; i < 10 && i < cornerX + 3; i++)
    for (var j = cornerY; j < 10 && j < cornerY + 3; j++)
      if (current == board[i][j])
        return false;
  return true;
}

function nextPos(x,y) { if(x<8) return [x+1,y]; else return [0,y+1]; }

function mkToCheck() { /// this one just builds your "suffled array"
  var toCheck = [];
  for(var i=0;i<9;i++) toCheck.push(i+1);
  for(var i = toCheck.length - 1; i > 0; i--) {
    var tmp;
    current = rand(i);
    tmp = toCheck[current];
    toCheck[current] = toCheck[i];
    toCheck[i] = tmp;
  }
  return toCheck;
}

/// THE THING IS HERE:
function buildBoard() {
  board = mkEmptyBoard(9,9);    
  var stck = [{'x':0,'y':0,'check': mkToCheck()}];    
  while(stck.length>0) {
    while(stck[0].check.length>0) {
      var ch = stck[0].check.shift();
      if(legalMove(stck[0].x, stck[0].y, ch)) {
        board[stck[0].x][stck[0].y] = ch;
        if(stck[0].y==8 && stck[0].x==8) return true; /// yay! board is ready
        var nextpos = nextPos(stck[0].x, stck[0].y);
        stck.unshift({'x':nextpos[0],'y':nextpos[1],'check':mkToCheck()});
        break;
      }
    }
    if(stck[0].check.length==0) { /// a bind alley -- revert!
      board[stck[0].x][stck[0].y]=0;
      stck.shift();
    }
  }
  board=mkEmptyBoard(); // clear the board as this is
  return false; /// a complete failure (hopefully notreached :))
}