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; }
};

  

最新文章

  1. HttpWebRequest请求时无法发送具有此谓词类型的内容正文。
  2. Atitit &#160;DbServiceV4qb9&#160;数据库查询类库v4 新特性
  3. 揭开HTTP网络协议神秘面纱系列(一)
  4. 李洪强iOS开发之initWithFrame,initWithCoder和aweakFormNib
  5. WEB黑客工具箱之LiveHttpHeaders介绍
  6. JavaScript之向文档中添加元素和内容的方法
  7. windows下fitness python版本安装测试
  8. leetcode先刷_Remove Duplicates from Sorted List II
  9. linuxmint卸载软件
  10. onclick事件触发 input type=“file” 上传文件
  11. .net core ef 通过dbfirst方式连接mysql数据库
  12. Java开发笔记(三十)大小数BigDecimal
  13. Powershell远程执行命令
  14. gstreamer如何查看相关插件信息(src/sink)?
  15. 阿里历年经典Java面试题汇总,想进BAT你还不快收藏!
  16. IntelliJ IDEA遇到Unable to parse template “Class”错误
  17. googletest进行单元测试(使用cmake编译)
  18. salt之pillar组件
  19. 【新题】OCP 062题库出现很多新题-6
  20. ubuntu tftp 配置

热门文章

  1. 图的遍历(搜索)算法(深度优先算法DFS和广度优先算法BFS)
  2. ionic之$ionicGesture手势(大坑)
  3. Scala集合和Java集合对应转换关系
  4. jQuery操作DOM元素
  5. enote笔记语言(1)
  6. Connect to the DSP on C6A8168/DM8168/DM8148 using CCS
  7. jquery 通过submit()方法 提交表单示例
  8. Nuclear开始
  9. JQuery中隐藏/显示事件函数
  10. 自定义 bundle 包的创建