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;
}
相关推荐
好开心啊没烦恼8 分钟前
Python 数据分析:计算,分组统计1,df.groupby()。听故事学知识点怎么这么容易?
开发语言·python·数据挖掘·数据分析·pandas
lljss20201 小时前
Python11中创建虚拟环境、安装 TensorFlow
开发语言·python·tensorflow
课堂剪切板1 小时前
ch03 部分题目思路
算法
山登绝顶我为峰 3(^v^)32 小时前
如何录制带备注的演示文稿(LaTex Beamer + Pympress)
c++·线性代数·算法·计算机·密码学·音视频·latex
Two_brushes.3 小时前
【算法】宽度优先遍历BFS
算法·leetcode·哈希算法·宽度优先
Python×CATIA工业智造4 小时前
Frida RPC高级应用:动态模拟执行Android so文件实战指南
开发语言·python·pycharm
十五年专注C++开发5 小时前
CMake基础:条件判断详解
c++·跨平台·cmake·自动化编译
我叫小白菜5 小时前
【Java_EE】单例模式、阻塞队列、线程池、定时器
java·开发语言
森焱森5 小时前
水下航行器外形分类详解
c语言·单片机·算法·架构·无人机
狐凄5 小时前
Python实例题:基于 Python 的简单聊天机器人
开发语言·python