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:

[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."], ["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]

经典的N皇后问题,我首先是用brute force,但是这样做的话一直会TLE:

 class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
vector<int> board(n);
vector<vector<string>> ret;
vector<string> tmpVec;
for(int i = ; i < n; ++i){
board[i] = i + ;//确保了上下左右不会有相邻的元素
}
vector<int> afterAdd(n);
vector<int> afterSub(n);
for(;;){
transform(board.begin(), board.end(), afterAdd.begin(),
              [](int i)->int{static int index = ; i += index; index++; return i;});
transform(board.begin(), board.end(), afterSub.begin(),
              [](int i)->int{static int index = ; i -= index; index++; return i;});
set<int>afterSubSet(afterSub.begin(), afterSub.end());
set<int>afterAddSet(afterAdd.begin(), afterAdd.end());
if(afterAddSet.size() == n && afterSubSet.size() == n){
for(int i = ; i < n; i++){
string tmp = "";
for(int j = ; j < n; ++j){
tmp.append(, j == board[i]- ? 'Q' : '.');
}
tmpVec.push_back(tmp);
tmp.clear();
}
ret.push_back(tmpVec);
tmpVec.clear();
}
if(!next_permutation(board.begin(), board.end())){
return ret;
break;
}
}
}
};

后来就只能使用dfs了,代码如下:

 class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
ret.clear();
memset(canUse, true, sizeof(canUse));
dfs(,n);
return ret;
} bool check(int pos, int line)
{
for(int i = ; i < line; ++i){
if(line - i == abs(pos - a[i])) //这一步很重要
return false; //相差n行的两个皇后的位置不可以也正好相差n个,那样一定是不可以的 }
return true;
} void dfs(int dep, int maxDep)
{
if(dep == maxDep){
vector<string> tmpVec;
for(int i = ; i < maxDep; ++i){
string tmp = "";
for(int j = ; j < maxDep; ++j){
tmp.append(, j == a[i] ? 'Q' : '.');
}
tmpVec.push_back(tmp);
tmp.clear();
}
ret.push_back(tmpVec);
tmpVec.clear();
}
for(int i = ; i < maxDep; ++i){
if(canUse[i] && check(i, dep)){
canUse[i] = false;
a[dep] = i;
dfs(dep + , maxDep);
canUse[i] = true;
}
}
}
private:
vector<vector<string>> ret;
int a[];
bool canUse[];
};

LeetCode OJ:N-Queens(N皇后问题)的更多相关文章

  1. LeetCode OJ 题解

    博客搬至blog.csgrandeur.com,cnblogs不再更新. 新的题解会更新在新博客:http://blog.csgrandeur.com/2014/01/15/LeetCode-OJ-S ...

  2. 【LeetCode OJ】Interleaving String

    Problem Link: http://oj.leetcode.com/problems/interleaving-string/ Given s1, s2, s3, find whether s3 ...

  3. 【LeetCode OJ】Reverse Words in a String

    Problem link: http://oj.leetcode.com/problems/reverse-words-in-a-string/ Given an input string, reve ...

  4. LeetCode OJ学习

    一直没有系统地学习过算法,不过算法确实是需要系统学习的.大二上学期,在导师的建议下开始学习数据结构,零零散散的一学期,有了链表.栈.队列.树.图等的概念.又看了下那几个经典的算法——贪心算法.分治算法 ...

  5. LeetCode OJ 297. Serialize and Deserialize Binary Tree

    Serialization is the process of converting a data structure or object into a sequence of bits so tha ...

  6. 备份LeetCode OJ自己编写的代码

    常泡LC的朋友知道LC是不提供代码打包下载的,不像一般的OJ,可是我不备份代码就感觉不舒服- 其实我想说的是- 我自己写了抓取个人提交代码的小工具,放在GitCafe上了- 不知道大家有没有兴趣 ht ...

  7. LeetCode OJ 之 Maximal Square (最大的正方形)

    题目: Given a 2D binary matrix filled with 0's and 1's, find the largest square containing all 1's and ...

  8. LeetCode OJ:Integer to Roman(转换整数到罗马字符)

    Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 t ...

  9. LeetCode OJ:Serialize and Deserialize Binary Tree(对树序列化以及解序列化)

    Serialization is the process of converting a data structure or object into a sequence of bits so tha ...

随机推荐

  1. head中的title显示在body中

    今天遇到一个问题,就是title中的内容会显示在body中 <head> <title>324234</title> </head> 网上搜了一下是说编 ...

  2. 在python3下使用OpenCV做离散余弦变换DCT及其反变换IDCT

    对图像处理经常用到DCT, Python下有很多带有DCT算法包, 这里使用OpenCV的DCT做变换, 并简单置0部分数据, 再查看反变换图像的效果. import numpy as np impo ...

  3. Elasticsearch、MongoDB、Hadoop适用场景

    如果你仅仅想要通过关键字和简单的分析,那么Elasticsearch可以完成任务: 如果你需要查询文档,并且包含更加复杂的分析过程,那么MongoDB相当适合: 如果你有一个海量的数据,需要大量不同的 ...

  4. 20145303 实验一 Java开发环境的熟悉(Linux + Eclipse)

    20145303 实验一 Java开发环境的熟悉(Linux + Eclipse) 实验题目(4):实现学生成绩管理功能,并进行测试 思路: 对于实现学生成绩管理(student performanc ...

  5. 20145310 《Java程序设计》第5周学习总结

    20145310 <Java程序设计>第5周学习总结 教材学习内容总结 本周主要进行第八章和第九章的学习. java中所有的错误都会打包为对象,可以try catch代表错误的对象后做一些 ...

  6. ubuntu 12.04网络设置

    1.服务器版本 设置IP地址 ubuntu 12.04的网络设置文件是/etc/network/interfaces,打开文件,会看到 auto lo iface lo inet loopback 这 ...

  7. 解读:hadoop压缩格式

    Hadoop中用得比较多的4种压缩格式:lzo,gzip,snappy,bzip2.它们的优缺点和应用场景如下: 1). gzip压缩 优点:压缩率比较高,而且压缩/解压速度也比较快:hadoop本身 ...

  8. 如何升级到python3版本并且安装pip3

    如何升级到python3版本并且安装pip3 准备: Python-3.5.2.tar.xz pip-8.1.2.tar.gz setuptools-24.0.2.zip 步骤: 1.自定义编译安装p ...

  9. [Network Architecture]Xception 论文笔记(转)

    文章来源 论文:Xception: Deep Learning with Depthwise Separable Convolutions 论文链接:https://arxiv.org/abs/161 ...

  10. 酷到没朋友—— Cafflano便携式手磨手冲一体壶

    又一款外国新玩具~ 设计紧凑,手磨.滤架.滤壶融合的毫无ps痕迹! 简直是出差旅行,杀人越货必备良品!废话不多说,上图: 肿么样,一壶在手,天下我有~~~哈哈哈~~~