八皇后问题是一个经典的算法问题,目的是在8×8的棋盘上放置8个皇后,使得每个皇后都不会互相攻击,即任意两个皇后都不在同一行、同一列或同一对角线上。以下是Java实现八皇后问题的代码:

public class EightQueens {
    private int[] queens; // 皇后位置数组
    private int count; // 解的个数

    public EightQueens() {
        queens = new int[8];
        count = 0;
    }

    // 放置皇后
    private void placeQueen(int row) {
        if (row == 8) { // 找到一个解
            count++;
            printSolution();
            return;
        }
        for (int col = 0; col < 8; col++) { // 遍历列
            boolean canPlace = true;
            for (int i = 0; i < row; i++) { // 遍历已放置的皇后
                if (queens[i] == col || queens[i] - i == col - row || queens[i] + i == col + row) {
                    // 判断是否在同一列、同一对角线
                    canPlace = false;
                    break;
                }
            }
            if (canPlace) { // 可以放置皇后
                queens[row] = col;
                placeQueen(row + 1);
            }
        }
    }

    // 打印解
    private void printSolution() {
        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                if (queens[i] == j) {
                    System.out.print("Q ");
                } else {
                    System.out.print(". ");
                }
            }
            System.out.println();
        }
        System.out.println();
    }

    // 获取解的个数
    public int getCount() {
        return count;
    }

    public static void main(String[] args) {
        EightQueens eq = new EightQueens();
        eq.placeQueen(0);
        System.out.println("共有" + eq.getCount() + "个解");
    }
}

该程序使用递归的方式实现,从第一行开始遍历每一列,判断是否可以放置皇后。如果可以放置,就将皇后放在当前位置,然后递归到下一行。如果找到一个解,就打印解并返回上一行继续遍历。如果遍历完所有行仍没有找到解,程序就结束。

Java实现八皇后问题

原文地址: http://www.cveoy.top/t/topic/bsAE 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录