繁体   English   中英

解决N个皇后时的数组索引超出范围异常

[英]Array Index Out of Bounds Exception while solving N Queens

我正在使用递归回溯来解决8个皇后问题的代码(将n个国际象棋皇后放置在n×n板上,以便没有一个皇后互相攻击)。

我的任务是创建两个方法:编写一个公共resolveQueens(int n)方法来解决nxn板的问题

编写一个私有的递归placeQueen(board, column)方法以尝试将皇后放置在指定的列中。

到目前为止,我已经在程序中编写了以下代码:

public class Queen {

    public static boolean isLegal(int[] board, int n) {
        for (int i = 0; i < n; i++) {
            if (board[i] == board[n]) {
                return false;
            }
            if ((board[i] - board[n]) == (n - i)) {
                return false;
            }
            if ((board[n] - board[i]) == (n - i)) {
                return false;
            }
        }
        return true;

    }

    public static void solver(int n) {
        int[] board = new int[n];
        PlaceQueen(board, 0);
    }

    private static int[] PlaceQueen(int[] board, int column) {
        int n = board.length;
        if (column == n); else {
            for (int row = 0; row < n; row++) {
                board[column] = row;
                if (isLegal(board, column)) {
                    PlaceQueen(board, column + 1);
                }

            }
        }
        return (board);
    }

    public static void main(String[] args) {
        int n = Integer.parseInt(args[0]);
        solver(n);
    }
}

我的程序成功编译,但是每当我尝试运行它时,都会出现此错误。

线程“主”中的异常java.lang.ArrayIndexOutOfBoundsException:Queen.main(Queen.java:39)为0

关于应该在哪里编辑代码以摆脱此异常的反馈的任何建议?

您是否向程序提供参数? 它期望有一个integer参数。

public static void main(String[] args) {
       int n = Integer.parseInt(args[0]);
       solver(n);           
    }

如果您尝试访问不在args数组范围内的索引,则它将引发java.lang.ArrayIndexOutOfBoundsException

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM