题目:

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.

Example

There exist two distinct solutions to the 4-queens puzzle:

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

 

题解:

  此题需要注意的是对角线因素,不仅不能对角线相邻,而且不能在一条对角线上,中间隔着一个也不行!刚开始没注意,花了一个多小时才明白过来。。。

Solution 1 ()

class Solution {
public:
void dfs(vector<vector<string>>& res, vector<string>& v, int n, vector<int>& pos, int row) {
if(row >= n) {
res.push_back(v);
return;
}
for(int col=; col<n; ++col) {
if (!isValid(pos, row, col)) {
continue;
}
v[row][col] = 'Q';
pos[row] = col;
dfs(res, v, n, pos, row + );
pos[row] = -;
v[row][col] = '.';
}
}
bool isValid(vector<int>& pos, int row, int col) {
for (int i = ; i < row; ++i) {
if (pos[i] == col || abs(row - i) == abs(col - pos[i])) {
return false;
}
}
return true;
}
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> res;
vector<string> v(n, string(n, '.'));
vector<int> pos(n, -);
dfs(res, v, n, pos, );
return res;
}
};

Solution 1.2 () from here

class Solution {
private:
vector<vector<string> > res;
public:
vector<vector<string> > solveNQueens(int n) {
vector<string>cur(n, string(n,'.'));
helper(cur, );
return res;
}
void helper(vector<string> &cur, int row)
{
if(row == cur.size())
{
res.push_back(cur);
return;
}
for(int col = ; col < cur.size(); col++)
if(isValid(cur, row, col))
{
cur[row][col] = 'Q';
helper(cur, row+);
cur[row][col] = '.';
}
} //判断在cur[row][col]位置放一个皇后,是否是合法的状态
//已经保证了每行一个皇后,只需要判断列是否合法以及对角线是否合法。
bool isValid(vector<string> &cur, int row, int col)
{
//列
for(int i = ; i < row; i++)
if(cur[i][col] == 'Q')return false;
//右对角线(只需要判断对角线上半部分,因为后面的行还没有开始放置)
for(int i = row-, j=col-; i >= && j >= ; i--,j--)
if(cur[i][j] == 'Q')return false;
//左对角线(只需要判断对角线上半部分,因为后面的行还没有开始放置)
for(int i = row-, j=col+; i >= && j < cur.size(); i--,j++)
if(cur[i][j] == 'Q')return false;
return true;
}
};

Solution 1.3 ()

class Solution2 {
public:
std::vector<std::vector<std::string> > solveNQueens(int n) {
std::vector<std::vector<std::string> > res;
std::vector<std::string> nQueens(n, std::string(n, '.'));
solveNQueens(res, nQueens, , n);
return res;
}
private:
void solveNQueens(std::vector<std::vector<std::string> > &res, std::vector<std::string> &nQueens, int row, int &n) {
if (row == n) {
res.push_back(nQueens);
return;
}
for (int col = ; col != n; ++col)
if (isValid(nQueens, row, col, n)) {
nQueens[row][col] = 'Q';
solveNQueens(res, nQueens, row + , n);
nQueens[row][col] = '.';
}
}
bool isValid(std::vector<std::string> &nQueens, int row, int col, int &n) {
//check if the column had a queen before.
for (int i = ; i != row; ++i)
if (nQueens[i][col] == 'Q')
return false;
//check if the 45° diagonal had a queen before.
for (int i = row - , j = col - ; i >= && j >= ; --i, --j)
if (nQueens[i][j] == 'Q')
return false;
//check if the 135° diagonal had a queen before.
for (int i = row - , j = col + ; i >= && j < n; --i, ++j)
if (nQueens[i][j] == 'Q')
return false;
return true;
}
};

【Lintcode】033.N-Queens的更多相关文章

  1. 【Lintcode】033.N-Queens II

    题目: Follow up for N-Queens problem. Now, instead outputting board configurations, return the total n ...

  2. 【lintcode】 二分法总结 I

     二分法:通过O(1)的时间,把规模为n的问题变为n/2.T(n) = T(n/2) + O(1) = O(logn). 基本操作:把长度为n的数组,分成前区间和后区间.设置start和end下标.i ...

  3. 【Lintcode】074.First Bad Version

    题目: The code base version is an integer start from 1 to n. One day, someone committed a bad version ...

  4. 【LintCode】转换字符串到整数

    问题描述: 实现atoi这个函数,将一个字符串转换为整数.如果没有合法的整数,返回0.如果整数超出了32位整数的范围,返回INT_MAX(2147483647)如果是正整数,或者INT_MIN(-21 ...

  5. 【LintCode】判断一个字符串是否包含另一个字符串的所有字符

    问题描述: 比较两个字符串A和B,确定A中是否包含B中所有的字符.字符串A和B中的字符都是 大写字母. 样例 给出 A = "ABCD" B = "ACD",返 ...

  6. 【LintCode】链表求和

    问题分析: 我们通过遍历两个链表拿到每个位的值,两个值加上前一位进位值(0或者1)模10就是该位的值,除以10就是向高位的进位值(0或者1). 由于两个链表可以不一样长,所以要及时判断,一旦为null ...

  7. 【LintCode】删除链表中的元素

    问题分析: 声明当前指针和上一个指针即可. 问题求解: public class Solution { public ListNode removeElements(ListNode head, in ...

  8. 【LintCode】计算两个数的交集(二)

    问题分析: 用两个指针分别遍历即可. 问题求解: public class Solution { /** * @param nums1 an integer array * @param nums2 ...

  9. 【LintCode】计算两个数的交集(一)

    问题分析: 既然返回值没有重复,我们不妨将结果放进set中,然后对两个set进行比较. 问题求解: public class Solution { /** * @param nums1 an inte ...

随机推荐

  1. Java下HttpUnit和Jsoup的Http抓取

    简单记录下:搜集信息-分析问题-解决问题 关于html文档的操作现成库有: HttpUnit 很老了,不更了 http://www.httpunit.org/  20 May 2008 HttpUni ...

  2. dede二级导航与二级栏目 ----内容介绍二级导航

    {dede:channelartlist typeid='top'}//如果只需要拿一列,则需要使用row='1'这个属性否则会根据子频道的数目循环输出 <a href="{dede: ...

  3. 一套ui满足ios与android界面

    1.android 画布宽高720*1280的标准来切图生成xhdpi标准图,后自动生成mdpi.hdpi.xhdpi.xxhdpi四套图. 2.ios画布宽高640 x 1136的标准来切图生成xh ...

  4. 12 nginx URL 重写 ecshop案例

    一:URL 重写 ecshop案例 Rewrite语法 Rewrite 正则表达式 定向后的位置 模式 Goods-3.html ---->Goods.php?goods_id=3 goods- ...

  5. cesium学习--初识

    一.Cesium 官方介绍:CesiumJS是一个开源的JavaScript库,用于世界级的3D地球仪和地图.任务是为静态和时间动态的内容创建领先的3D地球和地图,具有最好的性能.精度.视觉质量.平台 ...

  6. git查看某一次commit里面的内容,即本次commit相对于原来的版本进行了哪些修改

    1 知道commit id的话 git show commit-id 2 想要查看某次commit的某个文件进行了哪些修改 git show commit-id filename

  7. 空间Rm的任意两个范数都互相等价

  8. RocksDB

    RocksDB RocksDB is a high performance[1][2][3][4][5] embedded database for key-value data. It is a f ...

  9. mooc课程mit6.00.1x--problem set1解决方法

    counting vowels: 计算字符串中含有元音字母aeiou的数量 char = 'azcbobobegghakl' num = 0 #利用in方法直接查找字符串char中含有的元音字母数量 ...

  10. BCH硬分叉在即,Bitcoin ABC和NChain两大阵营PK

    混迹币圈,我们都知道,BTC分叉有了BCH,而近期BCH也将面临分叉,这次分叉将是Bitcoin ABC和NChain两大阵营的较量,最后谁能成为主导,我们拭目以待. 比特币现金(BCH)的价格自上周 ...