C++:N皇后

N皇后

问题描述

  在一个 n × n n\times n n×n的棋盘上摆放 n n n个皇后,要求任意两个皇后不能冲突,即任意两个皇后不在同一行、同一列或者同一斜线上。
算法基本思想

  将第 i i i个皇后摆放在第 i i i行, i i i从1开始,每个皇后都从第1列开始尝试。尝试时判断在该列摆放皇后是否与前面的皇后有冲突,如果没有冲突,则在该列摆放皇后,并考虑摆放下一个皇后;如果有冲突,则考虑下一列。如果该行没有合适的位置,回溯到上一个皇后,考虑在原来位置的下一个位置上继续尝试摆放皇后...,直到找到所有合理摆放方案。

C++代码

cpp 复制代码
#include<iostream>
#include<vector>
using namespace std;

class Solution{
public:
    vector< vector<string> > result;
    void backTrack(int n, int row, vector<string>& chessboard) {
        if(row == n) {
            result.push_back(chessboard);
            return ;
        } 
        for(int col = 0; col < n; col++) {
            if(isValid(row, col, chessboard, n)) {
                chessboard[row][col] = 'Q';
                backTrack(n, row + 1, chessboard);
                chessboard[row][col] = '.';
            }
        }
    }
   
    bool isValid(int row, int col, vector<string>& chessboard, int n) {
        for(int i = 0; i < row; i++) {
            if(chessboard[i][col] == 'Q') {
                return false;
            }
        }
        
        for(int i = row-1, j = col-1; i >= 0 && j>= 0; i--, j--) {
            if(chessboard[i][j] == 'Q') {
                return false;
            }
        }

        for(int i = row-1, j = col+1; i >=0 && j < n; i--, j++) {
            if(chessboard[i][j] == 'Q') {
                return false;
            }
        }
        return true;
    }
    
    vector< vector<string> > solveQueen(int n) {
        result.clear();
        vector<string> chessboard(n, string(n, '.'));
        backTrack(n, 0, chessboard);
        return result;
    }
};

int main() {
    int n;
    cin >> n;
    Solution solution;
    solution.solveQueen(n);
    for(int i = 0; i < n; i++) {
		for(int j = 0; j < n; j++) {
			cout << solution.result[i][j] << endl;
		}
		cout << endl;
	}	
    return 0;
}
相关推荐
memcpy04 分钟前
LeetCode 2144. 打折购买糖果的最小开销【贪心】
算法·leetcode·职场和发展
在繁华处4 分钟前
Java从零到熟练(十一):Spring框架入门
java·开发语言·spring
十五年专注C++开发7 分钟前
cereal 库:C++ 序列化的轻量之选
开发语言·c++·序列化·反序列化·cereal
lqqjuly17 分钟前
设计模式:理论、架构与 C++ 实现—SOLID原则到23 种经典模式
c++·设计模式·架构
BestOrNothing_201519 分钟前
C++零基础到工程实战(5.2.8)多文件声明定义函数和全局变量
c++·c++多文件编译·.h头文件·.cpp·函数声明定义
星卯教育tony27 分钟前
2026年全国青少年信息素养大赛主题应用 数字守艺人 丝路新城 星火征程 智传民韵 c++ python scratch 所有真题免费分享
开发语言·c++
z落落39 分钟前
C# 继承:父子构造函数 + base 关键字 +五大访问修饰符(同项目+跨项目 全覆盖)
开发语言·c#
day day day ...1 小时前
MyBatis / MyBatis-Plus 动态 SQL 中 OGNL 表达式的常见陷阱与源码分析
java·开发语言·mybatis
basketball6161 小时前
C++ bitset 头文件完全指南
开发语言·c++
Kiling_07041 小时前
Java IO流:字节流实战与性能优化
java·开发语言·php