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. 播放48KHZ有1S的停顿

    两个音频文件: /usr/lib/gstreamer-0.10/libgstflump3dec.so /usr/lib/gstreamer-0.10/libgstflumpegdemux.so

  2. Python中正则模块re.compile、re.match及re.search函数用法

    import rehelp(re.compile)'''输出结果为:Help on function compile in module re: compile(pattern, flags=0) C ...

  3. SQL学习笔记之B+树

    0x00 概述 要描述清楚B+树,得先了解二叉查找数,平衡二叉树. 0x01 二叉查找树 任意节点,它的左子树如果不为空,那么左子树上所有节点的值都小于根节点的值:任意节点,他的右子树如果不为空,那么 ...

  4. TCP/UDP 端口

    端口说明 小于1024的端口通常运行一些网络服务 大于1024的端口用来与远程机器建立连接 TCP端口 = 回显 = 丢弃 = 在线用户 = 时间服务 = 网络状态 = 每日引用 = 消息发送 = 字 ...

  5. Android studio通过连接蓝叠模拟器大幅提高速度!

    因为我的电脑是X200,集成显卡,不支持Opengl 2.0,很多安卓模拟器都不能用(夜神.海马玩,mumu等)最后发现蓝叠. 首先WIN+R,CMD,输入ADB,如果没有命令信息,说明我们需要在PA ...

  6. 20145327实验二Java面向对象程序设计

    Java面向对象程序设计 实验内容 初步掌握单元测试和TDD 理解并掌握面向对象三要素:封装.继承.多态 初步掌握UML建模 熟悉S.O.L.I.D原则 了解设计模式 伪代码,产品代码,测试代码的应用 ...

  7. 利用MacBook Air入侵无线网络

    目前无线网络的加密方式主要有WEP,WPA/WPA2.这是最常看到的加密方式,最近由于需要,专门去研究了一下如何入侵无线网络. 1.入侵WEP加密的无线网络 WEP加密方式现在已经很不安全了,因为只要 ...

  8. DOS/BAT批处理if exist else 语句的几种用法

    在DOS批处理命令中常常会通过if语句来进行判断来执行下面的命令, 那么批处理if语句怎么用呢,下面学无忧小编就来说说有关批处理if以及if exist else语句的相关内容.一.批处理if书写格式 ...

  9. webservice的测试案例

    1.服务器端 服务器接口Test_service.java package com.xiaostudy; /** * @desc 服务器接口 * @author xiaostudy * */ publ ...

  10. install opencv

    OpenCV是一个基于开源发行的跨平台计算机视觉库,它轻量级而且高效——由一系列 C 函数和少量 C++ 类构成,同时提供了Python.Ruby.MATLAB等语言的接口,实现了图像处理和计算机视觉 ...