gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:59:31 25 4
gpt4 key购买 nike

我一直在尝试编写一个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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com