当前位置: 首页 > article >正文

LeetCode51. N-Queens

文章目录

    • 一、题目
    • 二、题解

一、题目

The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order.

Each solution contains a distinct board configuration of the n-queens’ placement, where ‘Q’ and ‘.’ both indicate a queen and an empty space, respectively.

Example 1:

Input: n = 4
Output: [[“.Q…”,“…Q”,“Q…”,“…Q.”],[“…Q.”,“Q…”,“…Q”,“.Q…”]]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above
Example 2:

Input: n = 1
Output: [[“Q”]]

Constraints:

1 <= n <= 9

二、题解

class Solution {
public:
    vector<vector<string>> res;
    bool isValid(vector<string>& chessboard,int row,int col,int n){
        //检查列
        for(int i = 0;i < row;i++){
            if(chessboard[i][col] == 'Q') return false;
        }
        //检查45度角
        for(int i = row - 1,j = col - 1;i >= 0 && j >= 0;i--,j--){
            if(chessboard[i][j] == 'Q') return false;
        }
        //检查135度角
        for(int i = row - 1,j = col + 1;i >= 0 && j < n;i--,j++){
            if(chessboard[i][j] == 'Q') return false;
        }
        return true;
    }
    void backtracing(vector<string>& chessboard,int row,int n){
        if(row == n){
            res.push_back(chessboard);
            return;
        }
        for(int i = 0;i < n;i++){
            if(isValid(chessboard,row,i,n)){
                chessboard[row][i] = 'Q';
                backtracing(chessboard,row+1,n);
                chessboard[row][i] = '.';
            }
        }
    }
    vector<vector<string>> solveNQueens(int n) {
        vector<string> chessboard(n,string(n,'.'));
        backtracing(chessboard,0,n);
        return res;
    }
};

http://www.kler.cn/news/148377.html

相关文章:

  • java后端实现登录退出功能,并用过滤器验证
  • android trace文件的抓取与查看方法
  • 【Lidar】基于Python的点云数据下采样+体素显示
  • tauri中使用rust调用动态链接库例子(使用libloading库和libc库)
  • ubuntu22.04 arrch64版在线安装java环境
  • C语言-指针讲解(3)
  • 用通俗的方式讲解Transformer:从Word2Vec、Seq2Seq逐步理解到GPT、BERT
  • 人机交互3——多主题多轮对话
  • TOD和PPS精确时间同步技术
  • C#面向对象
  • 2023网络安全产业图谱
  • 02-Java集合之双列集合,如HashMap,Hashtable,Properties,TreeMap的底层结构
  • 人工智能技术发展漫谈
  • 【Linux】信号
  • 《2023全球隐私计算报告》正式发布!
  • C语言错误处理之“非局部跳转<setjmp.h>头文件”
  • python 爬虫之 爬取网站信息并保存到文件
  • C++初阶--String类的使用
  • TCP 传输可靠性问题
  • DMX512协议及对接口电路的分析
  • openssl版本号解析
  • HTML新手入门笔记整理:HTML基本标签
  • 【DevOps】SonarQube 指标解读
  • Vue3 实现elementPlus的table列宽调整和拖拽
  • 最新版灵沐V3.3微信资源类小程序源码支持流量主
  • C语言面试之旅:掌握基础,探索深度(面试实战之c语言关键词中篇)
  • 在Spring Boot中使用ECharts绘制数据图表
  • 智慧化工~工厂设备检修和保全信息化智能化机制流程
  • 火狐挂代理访问问题Software is preventing Firefox from safely connecting to this site
  • Blazor Table 实现获取当前选中行的功能