LeetCode OJ:N-Queens(N皇后问题)
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皇后问题)的更多相关文章
- LeetCode OJ 题解
博客搬至blog.csgrandeur.com,cnblogs不再更新. 新的题解会更新在新博客:http://blog.csgrandeur.com/2014/01/15/LeetCode-OJ-S ...
- 【LeetCode OJ】Interleaving String
Problem Link: http://oj.leetcode.com/problems/interleaving-string/ Given s1, s2, s3, find whether s3 ...
- 【LeetCode OJ】Reverse Words in a String
Problem link: http://oj.leetcode.com/problems/reverse-words-in-a-string/ Given an input string, reve ...
- LeetCode OJ学习
一直没有系统地学习过算法,不过算法确实是需要系统学习的.大二上学期,在导师的建议下开始学习数据结构,零零散散的一学期,有了链表.栈.队列.树.图等的概念.又看了下那几个经典的算法——贪心算法.分治算法 ...
- 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 ...
- 备份LeetCode OJ自己编写的代码
常泡LC的朋友知道LC是不提供代码打包下载的,不像一般的OJ,可是我不备份代码就感觉不舒服- 其实我想说的是- 我自己写了抓取个人提交代码的小工具,放在GitCafe上了- 不知道大家有没有兴趣 ht ...
- 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 ...
- 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 ...
- 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 ...
随机推荐
- 如何通过包名打开手机里的APP
目前已知的打开APP的方式有两种, 一种是通过openUrl打开,这种有一个严重的问题,即必须添加白名单,白名单之外的APP即时安装了也无法打开. 另一种就是今天的重点,通过包名打开APP.先上核心代 ...
- 资产证券化(ABS)+ 特殊目的信托(SPV)
资产证券化是指以基础资产未来所产生的现金流为偿付支持,通过结构化设计进行信用增级,在此基础上发行资产支持证券(Asset-backed Securities, ABS)的过程,通过将有形或者无形资产作 ...
- 优秀 H5 案例收集 vol.4(不定期更新)
重返木叶村 http://hyrz.qq.com/act/a20160113muyecun/index.html 飞越淘宝奇市 https://g.alicdn.com/fdilab/flyover- ...
- 20144303 《Java程序设计》第八周学习总结
20144303 <Java程序设计>第八周学习总结 教材学习内容总结 第十五章 1.日志API简介: java.util.logging包提供了日志功能相关类与接口,不必额外配置日志组件 ...
- IO多路复用客户端-服务器模型
IO多路复用服务器 -- 实现字符回射 服务器端 /************************************************************************* ...
- 收藏 19 个 ES6常用的简写技巧
代码精炼是每个有追求的程序所向往的,本文总结了19个JavaScript的简写技术,其中包括三元操作符.短路求值简写方式.声明变量简写方法等等,还有些自己的理解加上去:希望对你有帮助. 三元操作符 当 ...
- jdbctemplate中的queryForInt方法
今天才发现,原来spring 3.2.2之后,jdbctemplate中的queryForInt已经被取消了! 看下代码: 原来是这样写的: String sql = "SELECT cou ...
- 学Git,用Git ②
之前介绍了git的最核心功能游戏存档式的本地版本管理.这会我们介绍git剩下的两个核心功能:分支和远程仓库. 1.Git游戏存档进化版--Git分支 git分支的思想很有意思,git允许我们可以随时从 ...
- 深度学习:Keras入门(一)之基础篇【转】
本文转载自:http://www.cnblogs.com/lc1217/p/7132364.html 1.关于Keras 1)简介 Keras是由纯python编写的基于theano/tensorfl ...
- Exception in thread "main" redis.clients.jedis.exceptions.JedisDataException
这个版本默认是开启了保护模式,进入redis的文件夹下的src 输入(前提是得开启redis服务): ./redis-cli config set protected-mode "no&qu ...