leetcode:N-Queens II 【Java】

本文介绍了一种解决N皇后问题的方法,该方法不仅找出所有可能的解决方案配置,还计算了不同解决方案的数量。通过使用回溯算法,文章提供了一个Java实现示例,展示了如何有效地确定任意大小棋盘上放置皇后的所有非冲突布局。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、问题描述

Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.


二、问题分析

参考问题leetcode:N-Queens 【Java】

三、算法代码

public class Solution {
    public int totalNQueens(int n) {
        int [] total = new int [] {0};
        if (n <= 0) return total[0];
        char[][] board = new char[n][n];
        for (char[] row : board) {
            Arrays.fill(row, '.');
        }
        boolean[] col_occupied = new boolean[n];
        placeQueen(total, board, col_occupied, 0, n);
        return total[0];
    }
    private void placeQueen(int [] total, char[][] board, boolean[] col_occupied, int rowNum, int n) {
        if (rowNum == n) {
            total[0]++;
            return;
        }
        for (int colNum = 0; colNum < n; colNum++) {
            if (isValid(board, col_occupied, rowNum, colNum, n)){
                board[rowNum][colNum] = 'Q';
                col_occupied[colNum] = true;
                placeQueen(total, board, col_occupied, rowNum + 1, n);
                board[rowNum][colNum] = '.'; //回溯,尝试皇后rowNum的下一个位置
                col_occupied[colNum] = false;
            }
        }
    }
    private boolean isValid(char[][]board, boolean[] col_occupied, int row, int col, int n) {
        if (col_occupied[col]) return false;
        for (int i = 1; row - i >= 0 && col - i >= 0; i++) {//反对角斜线
            if (board[row - i][col - i] == 'Q') return false;
        }
        for (int i = 1; row - i >= 0 && col + i < n; i++) {//正对角斜线
            if (board[row - i][col + i] == 'Q') return false;
        }
        return true;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值