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

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.lryc.cn/news/247920.html

相关文章:

  • 前端vue3——html2canvas给网站截图生成宣传海报
  • C语言实现串的部分算法
  • UE5、CesiumForUnreal实现加载GeoJson绘制多面(MultiPolygon)功能(支持点选高亮)
  • pandas教程:USDA Food Database USDA食品数据库
  • 0基础学习VR全景平台篇第122篇:VR视频剪辑和输出 - PR软件教程
  • ucharts中,当数据为0时,不显示
  • React函数组件渲染两次
  • 人工智能 - 图像分类:发展历史、技术全解与实战
  • go标准库
  • 【Web安全】拿到phpMyAdmin如何获取权限
  • Python与GPU编程快速入门(一)
  • C语言--每日选择题--Day29
  • ESP32:物联网时代的神器
  • docker和docker-compose生产的容器,不在同一个网段,解决方式
  • 基于JavaWeb+SSM+Vue校园综合服务小程序系统的设计和实现
  • 私域运营:资源盘点及争取策略
  • 图书管理系统源码,图书管理系统开发,图书借阅系统源码整体功能演示
  • (C++)字符串相乘
  • 1992-2021年区县经过矫正的夜间灯光数据(GNLD、VIIRS)
  • RK3568笔记六:基于Yolov8的训练及部署
  • 【活动回顾】sCrypt在柏林B2029开发者周
  • 【SpringBoot3+Vue3】六【完】【番外篇】- (0-1临摹)
  • 生成式AI与大语言模型,东软已经准备就绪
  • Python爬虫遇到重定向URL问题时如何解决?
  • 【点云surface】无序点云快速三角化
  • el-select多选下拉框实现全选功能
  • Elasticsearch 聚合查询(Aggregation)详解
  • 数据库其它调优策略
  • 【AI认证笔记】NO.2人工智能的发展
  • Python与设计模式--观察者模式