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;
}
相关推荐
liO_Oil几秒前
(2024.9.19)在Python的虚拟环境中安装GDAL
开发语言·python·gdal安装
逝去的秋风8 分钟前
【代码随想录训练营第42期 Day61打卡 - 图论Part11 - Floyd 算法与A * 算法
算法·图论·floyd 算法·a -star算法
万物得其道者成16 分钟前
React Zustand状态管理库的使用
开发语言·javascript·ecmascript
zero_one_Machel17 分钟前
leetcode73矩阵置零
算法·leetcode·矩阵
学步_技术21 分钟前
Python编码系列—Python抽象工厂模式:构建复杂对象家族的蓝图
开发语言·python·抽象工厂模式
BeyondESH43 分钟前
Linux线程同步—竞态条件和互斥锁(C语言)
linux·服务器·c++
wn5311 小时前
【Go - 类型断言】
服务器·开发语言·后端·golang
青椒大仙KI111 小时前
24/9/19 算法笔记 kaggle BankChurn数据分类
笔记·算法·分类
^^为欢几何^^1 小时前
lodash中_.difference如何过滤数组
javascript·数据结构·算法
豆浩宇1 小时前
Halcon OCR检测 免训练版
c++·人工智能·opencv·算法·计算机视觉·ocr