当前位置: 首页 > news >正文

⭐算法OJ⭐N-皇后问题 II【回溯剪枝】(C++实现)N-Queens II

⭐算法OJ⭐N-皇后问题【回溯剪枝】(C++实现)N-Queens

问题描述

The n-queens puzzle is the problem of placing n n n queens on an n × n n \times n n×n chessboard such that no two queens attack each other.

Given an integer n, return the number of distinct solutions to the n-queens puzzle.

Example 1:
在这里插入图片描述

Input: n = 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown.

Example 2:

Input: n = 1
Output: 1
#include <iostream>
#include <vector>

using namespace std;

// 检查当前位置 (row, col) 是否可以放置皇后
bool isSafe(int row, int col, vector<int>& position) {
    for (int i = 0; i < row; i++) {
        // 检查列和对角线
        if (position[i] == col || abs(position[i] - col) == abs(i - row)) {
            return false;
        }
    }
    return true;
}

// 回溯函数
void solve(int row, vector<int>& position, int n, int& count) {
    // 如果当前行是最后一行,说明找到一个解
    if (row == n) {
        count++; // 解的数量加 1
        return;
    }

    // 尝试在当前行的每一列放置皇后
    for (int col = 0; col < n; col++) {
        if (isSafe(row, col, position)) { // 如果当前位置安全
            position[row] = col; // 记录当前行的皇后位置
            solve(row + 1, position, n, count); // 递归到下一行
            position[row] = -1; // 回溯,撤销皇后
        }
    }
}

// 主函数:求解 N-皇后问题的解的数量
int totalNQueens(int n) {
    int count = 0; // 记录解的数量
    vector<int> position(n, -1); // 记录每一行皇后的列位置,初始为 -1
    solve(0, position, n, count); // 从第 0 行开始回溯
    return count;
}

代码说明

  • isSafe 函数:
    • 检查当前位置 (row, col) 是否可以放置皇后。
    • 检查列和对角线是否有冲突。
  • solve 函数:
    • 使用回溯算法逐行尝试放置皇后。
    • 如果找到一个有效位置,递归到下一行。
    • 如果当前行所有位置都尝试完毕,回溯并撤销上一步的皇后。
  • totalNQueens 函数:
    • 初始化一个数组 position,用于记录每一行皇后的列位置。
    • 调用 solve 函数开始求解,并返回解的数量。

复杂度分析

  • 时间复杂度: O ( N ! ) O(N!) O(N!),因为每行有 N N N 种选择,且需要检查冲突。
  • 空间复杂度: O ( N ) O(N) O(N),用于存储每一行皇后的列位置和递归栈。

相关文章:

  • Spring中的@Qualifier和@Resource注解有什么不同?
  • redis 支持哪几种数据结构
  • 【FPGA开发】Verilog-数据截断实现四舍五入效果、模块化改造、对比Matlab验证,Modelsim覆盖率
  • SSLScan实战指南:全面检测SSL/TLS安全配置
  • 股指期货交割日每月几号?为什么是第三个周五还是倒数第二个周五?
  • 第十五届蓝桥杯Scratch12月stema选拔赛真题—消失的水母
  • STM32之Unix时间戳
  • 计算机毕业设计Python+DeepSeek-R1大模型医疗问答系统 知识图谱健康膳食推荐系统 食谱推荐系统 医疗大数据(源码+LW文档+PPT+讲解)
  • Spring-framework源码编译
  • 完全背包-一维数组
  • Apache Commons Lang3 和 Commons Net 详解
  • 【JavaScript】DOM和BOM是什么?
  • VUE3开发-9、axios前后端跨域问题解决方案
  • 1998-2022年各地级市第三产业占GDP比重数据/地级市第三产业占比数据(全市)
  • Leetcode 3472. Longest Palindromic Subsequence After at Most K Operations
  • XGBoost常见面试题(五)——模型对比
  • 如何在rust中解析 windows 的 lnk文件(快捷方式)
  • 23、什么是菱形继承【中高频】
  • el-tree(append与getNode与过滤)、深拷贝deepClone、监听addEventListener、
  • Aruco 库详解:计算机视觉中的高效标记检测工具
  • 哈尔滨seo整站优化/做企业推广的公司
  • 哪些是网站建设/品牌营销策划方案案例
  • 数码商城网站建设/免费发布信息网网站
  • 湖南省人民政府网站集约化建设/全专业优化公司
  • 在相亲网站做红娘/如何建网站不花钱
  • 湖南奶茶加盟网站建设/国外新闻最新消息