java - 优化 N Queens 代码以避免堆栈溢出

标签 java recursion stack-overflow

我一直在尝试编写一个java类来使用某种堆叠和递归来解决n皇后问题,答案存储在网格(二维数组)中,但是我遇到了一个死墙,即n=8时递归的堆栈溢出(最大递归深度达到2298) 所以我一直想知道是否有某种方法可以通过做一些复杂的事情来绕过这个死局,比如在java中分配更多的堆空间(如果可能的话?)或使用多线程(给我指出教程/示例)...或者请提供有关如何优化代码的建议... 提前致谢

    public void resoudre(){

        this.gridPile.push(copyGrid(grid));
        try{
            int row = gridPile.size()-1;
            if(gridPile.size()==0)row = 0;
            chooseGridSpace(this.grid, locateFirstAvailable(grid, row));
            if(gridPile.size() == this.taille){
                gridSolutions.push(copyGrid(grid));
                grid = gridPile.pop();
                boolean erronous = true;
                while(erronous){
                    try{
                        MakeNextUnavailable(grid, gridPile.size());
                        erronous = false;
                    }
                    catch(UnavailabilityException r1){
                        try{
                            grid = gridPile.pop();
                        }
                        catch(java.util.EmptyStackException r2){
                            return;
                        }
                    }
                }
            }

        }
        catch(InvalidPositionException e1){
            this.grid = gridPile.pop();
            boolean error = true;
            while(error){
                try{
                    MakeNextUnavailable(grid, gridPile.size());
                    error = false;
                }
                catch(UnavailabilityException er){
                    try{
                        this.grid = gridPile.pop();
                    }
                    catch(java.util.EmptyStackException err){
                        return;
                    }
                }
            }
        }
        catch(java.lang.ArrayIndexOutOfBoundsException e2){
            return;
        }
        this.resoudre();
    }

    private static void chooseGridSpace(int[][] grid, Position a){
        grid[a.getLigne()][a.getColonne()] = 1;
        fillNotAvailable(grid, a);
    }

最佳答案

直接回答:没有必要将整个网格插入堆栈,您可能希望将网格表示为 8 个整数的数组,表示每行的 Queen 位置。

真正的问题:您的代码太长而且太复杂。把事情简单化!皇后问题通常由 2 个函数(每个函数 <10 行)解决。很简单:

<子>

public static boolean isSolution(final int[] board)
{
    for (int i = 0; i < board.length; i++) {
        for (int j = i + 1; j < board.length; j++) {
            if (board[i] == board[j]) return false;     // same column "|"
            if (board[i]-board[j] == i-j) return false; // diagonal "\"
            if (board[i]-board[j] == j-i) return false; // diagonal "/"
        }
    }
    return true;
}

public static void solve(int depth, int[] board)
{
    if (depth == board.length && isSolution(board)) {
        outputSolution(board);
    }
    if (depth < board.length) {  // try all positions of the next row
        for (int i = 0; i < board.length; i++) {
            board[depth] = i;
            solve(depth + 1, board);
        }
    }
}

添加一些输出代码和主程序,就完成了! <子>

public static void outputSolution(final int[] board)
{
    System.out.println("--- Solution ---");
    for (int i = 0; i < board.length; i++) {
        for (int j = 0; j < board[i]; j++) System.out.print(" ");
        System.out.println("Q");
    }
}

public static void main(String[] args)
{
    int n = 8;
    solve(0, new int[n]);
}

关于java - 优化 N Queens 代码以避免堆栈溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1184734/

相关文章:

java - 行选择不随 JTable 中的行移动而移动

java - 如何在java中递归地在链表前面添加一个节点

c - 寻找迷宫路径的成本

c++ - 函数 main 中程序开头的 stackoverflow 错误

wcf - IIS 堆栈溢出

java - 使用 NetBeans 查找并替换整个项目中的代码块

java - 使用约束注释验证 json 不起作用

java - 如何在 Tomcat 6 中为 Hibernate 使用 JTA 支持?

c - c 上的递归计数

java - StackOverflow 错误,View.inflate 异常