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;
}
相关推荐
Ai财富密码6 分钟前
AI生成大屏可视化:数据智能驱动下的高维洞察与决策中枢
开发语言·人工智能·python·sdd
半兽先生9 分钟前
01阶段:大模型语言入门
开发语言·python
fengenrong10 分钟前
20260325
开发语言·c++
BestOrNothing_201512 分钟前
从C++结构体、类到 PID 控制器:运动控制初学者如何理解 C++ 工程代码
c++·面向对象·pid·运动控制·.h与.cpp·struct与class
l1t13 分钟前
执行python pyperformance基准测试的步骤
开发语言·python
chushiyunen13 分钟前
python中的for循环、dict、set、列表、数组等
开发语言·python
不光头强17 分钟前
力扣78子集题解
算法·leetcode·深度优先
IT 行者19 分钟前
实战LangChain4j集成MCP Server:让Java AI应用具备工具调用能力
java·开发语言·人工智能
独断万古他化20 分钟前
【算法通关】二叉树中的深搜:DFS 递归解题套路
算法·二叉树·深度优先·dfs·递归
㓗冽22 分钟前
2026.03.27(第三天)
数据结构·c++·算法