N-Queens

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.

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

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

算法1

这种棋盘类的题目一般是回溯法, 依次放置每行的皇后。在放置的时候,要保持当前的状态为合法,即当前放置位置的同一行、同一列、两条对角线上都不存在皇后。

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

算法2

上述判断状态是否合法的函数还是略复杂,其实只需要用一个一位数组来存放当前皇后的状态。假设数组为int state[n], state[i]表示第 i 行皇后所在的列。那么在新的一行 k 放置一个皇后后:

  • 判断列是否冲突,只需要看state数组中state[0…k-1] 是否有和state[k]相等;
  • 判断对角线是否冲突:如果两个皇后在同一对角线,那么|row1-row2| = |column1 - column2|,(row1,column1),(row2,column2)分别为冲突的两个皇后的位置
class Solution {
private:
vector<vector<string> > res;
public:
vector<vector<string> > solveNQueens(int n) {
vector<int> state(n, -1);
helper(state, 0);
return res;
}
void helper(vector<int> &state, int row)
{//放置第row行的皇后
int n = state.size();
if(row == n)
{
vector<string>tmpres(n, string(n,'.'));
for(int i = 0; i < n; i++)
tmpres[i][state[i]] = 'Q';
res.push_back(tmpres);
return;
}
for(int col = 0; col < n; col++)
if(isValid(state, row, col))
{
state[row] = col;
helper(state, row+1);
state[row] = -1;;
}
} //判断在row行col列位置放一个皇后,是否是合法的状态
//已经保证了每行一个皇后,只需要判断列是否合法以及对角线是否合法。
bool isValid(vector<int> &state, int row, int col)
{
for(int i = 0; i < row; i++)//只需要判断row前面的行,因为后面的行还没有放置
if(state[i] == col || abs(row - i) == abs(col - state[i]))
return false;
return true;
}
};

算法3:(算法2的非递归版)

class Solution {
private:
vector<vector<string> > res;
public:
vector<vector<string> > solveNQueens(int n) {
vector<int> state(n, -1);
for(int row = 0, col; ;)
{
for(col = state[row] + 1; col < n; col++)//从上一次放置的位置后面开始放置
{
if(isValid(state, row, col))
{
state[row] = col;
if(row == n-1)//找到了一个解,继续试探下一列
{
vector<string>tmpres(n, string(n,'.'));
for(int i = 0; i < n; i++)
tmpres[i][state[i]] = 'Q';
res.push_back(tmpres);
}
else {row++; break;}//当前状态合法,去放置下一行的皇后
}
}
if(col == n)//当前行的所有位置都尝试过,回溯到上一行
{
if(row == 0)break;//所有状态尝试完毕,退出
state[row] = -1;//回溯前清除当前行的状态
row--;
}
}
return res;
} //判断在row行col列位置放一个皇后,是否是合法的状态
//已经保证了每行一个皇后,只需要判断列是否合法以及对角线是否合法。
bool isValid(vector<int> &state, int row, int col)
{
for(int i = 0; i < row; i++)//只需要判断row前面的行,因为后面的行还没有放置
if(state[i] == col || abs(row - i) == abs(col - state[i]))
return false;
return true;
}
};

算法4(解释在后面)这应该是最高效的算法了

class Solution {
private:
vector<vector<string> > res;
int upperlim;
public:
vector<vector<string> > solveNQueens(int n) {
upperlim = (1 << n) - 1;//低n位全部置1
vector<string> cur(n, string(n, '.'));
helper(0,0,0,cur,0);
return res;
} void helper(const int row, const int ld, const int rd, vector<string>&cur, const int index)
{
int pos, p;
if ( row != upperlim )
{
pos = upperlim & (~(row | ld | rd ));//pos中二进制为1的位,表示可以在当前行的对应列放皇后
//和upperlim与运算,主要是ld在上一层是通过左移位得到的,它的高位可能有无效的1存在,这样会清除ld高位无效的1
while ( pos )
{
p = pos & (~pos + 1);//获取pos最右边的1,例如pos = 010110,则p = 000010
pos = pos - p;//pos最右边的1清0
setQueen(cur, index, p, 'Q');//在当前行,p中1对应的列放置皇后
helper(row | p, (ld | p) << 1, (rd | p) >> 1, cur, index+1);//设置下一行
setQueen(cur, index, p, '.');
}
}
else//找到一个解
res.push_back(cur);
} //第row行,第loc1(p)列的位置放置一个queen或者清空queen,loc1(p)表示p中二进制1的位置
void setQueen(vector<string>&cur, const int row, int p, char val)
{
int col = 0;
while(!(p & 1))
{
p >>= 1;
col++;
}
cur[row][col] = val;
}
};

这个算法主要参考博客N皇后问题的两个最高效的算法,主要看helper函数,参数row、ld、rd分别表示在列和两个对角线方向的限制条件下,当前行的哪些地方不能放置皇后。如下图

前三行放置了皇后,他们对第3行(行从0开始)的影响如下:                               本文地址

(1)列限制条件下,第3行的0、2、4列(紫色线和第3行的交点)不能放皇后,因此row = 101010

(2)左对角线限制条件下,第3行的0、3列(蓝色线和第3行的交点)不能放皇后,因此ld = 100100

(3)右对角线限制条件下,第3行的3、4、5列(绿色线和第3行的交点)不能放皇后,因此rd = 000111

~(row | ld | rd) = 010000,即第三行只有第1列能放置皇后。

在3行1列这个位置放上皇后,row,ld,rd对下一行的影响为:

row的第一位置1,变为111010

ld的第一位置1,并且向左移1位(因为左对角线对行的影响是依次向左倾斜的),变为101000

rd的第一位置1,并且向右移1位(因为右对角线对行的影响是依次向右倾斜的),变为001011

第4行状态如下图


N-Queens II

Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

这一题就是上一题的简化版了,我们只针对上面的算法2来求解这一题

class Solution {
private:
int res;
public:
int totalNQueens(int n) {
vector<int> state(n, -1);
res = 0;
helper(state, 0);
return res;
}
void helper(vector<int> &state, int row)
{//放置第row行的皇后
int n = state.size();
if(row == n)
{
res++;
return;
}
for(int col = 0; col < n; col++)
if(isValid(state, row, col))
{
state[row] = col;
helper(state, row+1);
state[row] = -1;;
}
} //判断在row行col列位置放一个皇后,是否是合法的状态
//已经保证了每行一个皇后,只需要判断列是否合法以及对角线是否合法。
bool isValid(vector<int> &state, int row, int col)
{
for(int i = 0; i < row; i++)//只需要判断row前面的行,因为后面的行还没有放置
if(state[i] == col || abs(row - i) == abs(col - state[i]))
return false;
return true;
} };

【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3801621.html

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

  1. LeetCode Single Number I / II / III

    [1]LeetCode 136 Single Number 题意:奇数个数,其中除了一个数只出现一次外,其他数都是成对出现,比如1,2,2,3,3...,求出该单个数. 解法:容易想到异或的性质,两个 ...

  2. [array] leetcode - 40. Combination Sum II - Medium

    leetcode - 40. Combination Sum II - Medium descrition Given a collection of candidate numbers (C) an ...

  3. LeetCode 137. Single Number II(只出现一次的数字 II)

    LeetCode 137. Single Number II(只出现一次的数字 II)

  4. LeetCode:路径总和II【113】

    LeetCode:路径总和II[113] 题目描述 给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径. 说明: 叶子节点是指没有子节点的节点. 示例:给定如下二叉树, ...

  5. LeetCode:组合总数II【40】

    LeetCode:组合总数II[40] 题目描述 给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合. candi ...

  6. [Leetcode] n queens ii n皇后问题

    Follow up for N-Queens problem. Now, instead outputting board configurations, return the total numbe ...

  7. [LeetCode] N-Queens II N皇后问题之二

    Follow up for N-Queens problem. Now, instead outputting board configurations, return the total numbe ...

  8. lintcode 中等题:N Queens II N皇后问题 II

    题目: N皇后问题 II 根据n皇后问题,现在返回n皇后不同的解决方案的数量而不是具体的放置布局. 样例 比如n=4,存在2种解决方案 解题: 和上一题差不多,这里只是求数量,这个题目定义全局变量,递 ...

  9. [LeetCode] 52. N-Queens II N皇后问题之二

    The n-queens puzzle is the problem of placing nqueens on an n×n chessboard such that no two queens a ...

  10. [LeetCode] 52. N-Queens II N皇后问题 II

    The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens ...

随机推荐

  1. (原)3.2 Zookeeper应用 - 数据的发布与订阅

    本文为原创文章,转载请注明出处,谢谢 数据的发布与订阅 1.应用 服务端监听数据改变,客户端创建/更新节点数据,客户端提供数据,服务端处理 2.原理 客户端监控节点数据改变事件(例如配置信息,下图的c ...

  2. 聊聊JVM的年轻代

    1.为什么会有年轻代 我们先来屡屡,为什么需要把堆分代?不分代不能完成他所做的事情么?其实不分代完全可以,分代的 唯一理由就是优化GC性能.你先想想,如果没有分代,那我们所有的对象都在一块,GC的时候 ...

  3. vue+ vue-router + webpack 踩坑之旅

    说是踩坑之旅 其实是最近在思考一些问题 然后想实现方案的时候,就慢慢的查到这些方案   老司机可以忽略下面的内容了 1)起因  考虑到数据分离的问题  因为server是express搭的   自然少 ...

  4. 原生JS:JSON对象详解

    JSON对象 支持到IE8,旧版的IE需要Polyfill 本文参考MDN做的详细整理,方便大家参考[MDN](https://developer.mozilla.org/zh-CN/docs/Web ...

  5. Googlehack之Github hack

    site:aircrk.com smtpsite:aircrk.com smtp @mail.comsite:aircrk.com root passwordsite:aircrk.com smtp ...

  6. Android开发学习——基础学习

    在微信公众号上,发现一个自学android的一个文章,觉得不错.对其进行小小总结,整理给大家. 1. 基础UI学习 Button/TextView/EditText/CheckBox/ImageVie ...

  7. 关于Ruby常用语法案例累积

    变量问题: 类变量和方法变量的区别是什么? 类变量:可以直接使用 方法变量:需要实例化后,才能使用该变量 案例一: class Person @@name = "Tom" @@na ...

  8. Linux备份ifcfg-eth0文件导致的网络故障问题

    今天在给一台操作系统为Oracle Linux Server release 5.7的服务器配置网络时,遇到了备份ifcfg-eth0配置文件,导致网卡无法绑定IP地址的情况.觉得是个有意思的案例,特 ...

  9. 35个java代码性能优化。。转

    前言 代码优化,一个很重要的课题.可能有些人觉得没用,一些细小的地方有什么好修改的,改与不改对于代码的运行效率有什么影响呢?这个问题我是这么考虑 的,就像大海里面的鲸鱼一样,它吃一条小虾米有用吗?没用 ...

  10. OpenGL ES无法获取贴图数据原因

    最近在做一个项目,要从贴图中获取图像数据,查了很多资料,也琢磨很久,获取到的数据都是0.终于在一次偶然的机会,发现了端倪,成功了. 不得不说这"一分灵感"真的很重要 以下是在获取贴 ...