22.八皇后问题-递归回溯


public class EightQueue {

    List<int[][]> datas = new ArrayList<>();

    static int count = 0;

    public static void main(String[] args) {
        int[][] queue = new int[8][8];
        putColumn(queue, 0);
        System.out.println(count);
    }

 
//    for 选择 in 选择列表:
//            # 做选择
//            将该选择从选择列表移除
//            路径.add(选择)
//            backtrack(路径, 选择列表)
//            # 撤销选择
//            路径.remove(选择)
//            将该选择再加入选择列表
    private static void putColumn(int[][] queue, int column) {
        if (column >= queue.length) {
            count++;
            return;
        }
        for (int j = 0; j < queue[column].length; j++) {
            if (canPut(queue, column, j)) {
                queue[column][j] = 1;
                putColumn(queue, column + 1);
                queue[column][j] = 0;
            }
        }
    }

    private static boolean canPut(int[][] board, int row, int col) {
        int n = 8;
        for (int i = 0; i < n; i++) {
            if (board[i][col] == 1)
                return false;
        }
        // 检查右上方是否有皇后互相冲突
        for (int i = row - 1, j = col + 1;
             i >= 0 && j < n; i--, j++) {
            if (board[i][j] == 1)
                return false;
        }
        // 检查左上方是否有皇后互相冲突
        for (int i = row - 1, j = col - 1;
             i >= 0 && j >= 0; i--, j--) {
            if (board[i][j] == 1)
                return false;
        }
        return true;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值