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. java容器的数据结构-ArrayList,LinkList,HashMap

    ArrayList: 初始容量为10,底层实现是一个数组,Object[] elementData 自动扩容机制,当添加一个元素时,数组长度超过了elementData.leng,则会按照1.5倍进行 ...

  2. 20145316《Java程序设计》第六周学习总结

    20143516许心远 <Java程序设计>第6周学习总结 教材学习内容总结 10.1.1 1.Java将输入/输出抽象化为串流,数据有来源及目的地,衔接两者的是串流对象. 2.若要将数据 ...

  3. redis 简单命令操作

    一.概述: 在该系列的前几篇博客中,主要讲述的是与Redis数据类型相关的命令,如String.List.Set.Hashes和Sorted-Set.这些命令都具有一个共同点,即所有的操作都是针对与K ...

  4. Visual C++的DLL

    动态链接库 (DLL) 是作为共享函数库的可执行文件. 动态链接提供了一种方法,使进程可以调用不属于其可执行代码的函数. 函数的可执行代码位于一个 DLL 中,该 DLL 包含一个或多个已被编译.链接 ...

  5. linux 登录数据库

    -h   地址 (例如:127.0.0.1,localhost) mysql -h 127.0.0.1 -u root -p

  6. Mysql主从架构报错-Fatal error: The slave I/O thread stops because master and slave have equal MySQL server UUIDs; these UUIDs must be different for replication to work...

    在搭建Mysql主从架构过程中,由于从服务器是克隆的主服务器系统,导致主从mysql uuid相同, Slave_IO无法启动,报错如下: The slave I/O thread stops bec ...

  7. [pixhawk笔记]5-uORB消息传递

    本文主要内容翻译自官方文档:https://dev.px4.io/en/middleware/uorb.html 在前一篇笔记中使用uORB完成消息传递,实现了一个简单示例程序,本文将对uORB进行系 ...

  8. Ubuntu16.04安装搜狗拼音输入法(中文输入法)[转]

    本文转载自:https://www.cnblogs.com/darklights/p/7722861.html 虽然网上有很多教程,但是我觉得我的很适合那些真正的小白... 1.下载文件 由于我要给多 ...

  9. Python学习笔记(十二)—Python3中pip包管理工具的安装【转】

    本文转载自:https://blog.csdn.net/sinat_14849739/article/details/79101529 版权声明:本文为博主原创文章,未经博主允许不得转载. https ...

  10. MAC OS X的命令行技巧

    ##透明度#降低透明度defaults write com.apple.universalaccess reduceTransparency -bool true#恢复默认透明度defaults wr ...