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;
}
相关推荐
xin007hoyo37 分钟前
算法笔记.染色法判断二分图
数据结构·笔记·算法
mozun202039 分钟前
VS BUG(6) LINK : fatal error LNK1158: 无法运行“rc.exe”
c++·bug·vs·链接器·资源文件
夜夜敲码42 分钟前
C语言教程(十八):C 语言共用体详解
c语言·开发语言
大学生亨亨1 小时前
go语言八股文(五)
开发语言·笔记·golang
raoxiaoya1 小时前
同时安装多个版本的golang
开发语言·后端·golang
whoarethenext2 小时前
初始https附带c/c++源码使用curl库调用
服务器·c++·qt·https·curl
cloues break.3 小时前
C++进阶----多态
开发语言·c++
我不会编程5553 小时前
Python Cookbook-6.10 保留对被绑定方法的引用且支持垃圾回收
开发语言·python
এ᭄画画的北北3 小时前
力扣-234.回文链表
算法·leetcode·链表
道剑剑非道3 小时前
QT开发技术【qcustomplot 曲线与鼠标十字功能】
开发语言·qt·计算机外设