N-Queens
2024-09-25 22:18:23
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q'
and '.'
both indicate a queen and an empty space respectively.
For example,
There exist two distinct solutions to the 4-queens puzzle:
分析: 著名的N皇后问题,可以采用一位数组来代替二维数组,利用回溯,注意皇后行走的条件
class Solution {
public:
bool isOk(int start,int value, const vector<int>& array){
for(int i =start-1; i>=0; i--)
if((array[i]==value) || (abs(array[i]-value)==abs(start-i)))
return false;
if(abs(array[start-1]-value)==1)
return false;
return true;
}
void Queen(int start, vector<int>& array, vector<vector<int>> & res ){
//cout << start <<endl;
if(start == array.size()){
res.push_back(array);
return;
}
for(int i =0; i< array.size(); i++){
if(isOk(start, i, array)){
// cout <<"hello"<<endl;
array[start] =i;
Queen(start+1, array, res);
} }
return;
} void convert(const vector<vector<int>> res, vector<vector<string>>& str){
for(vector<int> t: res){
int n = t.size();
vector<string> strlist;
for(int i=0; i<n; i++){
string s(n,'.');
s[t[i]] = 'Q';
strlist.push_back(s);
}
str.push_back(strlist); } }
vector<vector<string>> solveNQueens(int n) {
vector<vector<int>> res;
vector<vector<string>> str;
if(n==0)
return str;
vector<int> array(n,0);
for(int i =0; i< n; i++){
array[0] =i;
Queen(1,array,res);
}
convert(res,str);
return str; }
};
最新文章
- HttpWebRequest请求时无法发送具有此谓词类型的内容正文。
- Atitit &#160;DbServiceV4qb9&#160;数据库查询类库v4 新特性
- 揭开HTTP网络协议神秘面纱系列(一)
- 李洪强iOS开发之initWithFrame,initWithCoder和aweakFormNib
- WEB黑客工具箱之LiveHttpHeaders介绍
- JavaScript之向文档中添加元素和内容的方法
- windows下fitness python版本安装测试
- leetcode先刷_Remove Duplicates from Sorted List II
- linuxmint卸载软件
- onclick事件触发 input type=“file” 上传文件
- .net core ef 通过dbfirst方式连接mysql数据库
- Java开发笔记(三十)大小数BigDecimal
- Powershell远程执行命令
- gstreamer如何查看相关插件信息(src/sink)?
- 阿里历年经典Java面试题汇总,想进BAT你还不快收藏!
- IntelliJ IDEA遇到Unable to parse template “Class”错误
- googletest进行单元测试(使用cmake编译)
- salt之pillar组件
- 【新题】OCP 062题库出现很多新题-6
- ubuntu tftp 配置