[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 attack each other.

Given an integer n, return the number of distinct solutions to the n-queens puzzle.
Example:
Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."], ["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]

这道题是之前那道 N-Queens 的延伸,说是延伸其实我觉得两者顺序应该颠倒一样,上一道题比这道题还要稍稍复杂一些,两者本质上没有啥区别,都是要用回溯法 Backtracking 来解,如果理解了之前那道题的思路,此题只要做很小的改动即可,不再需要求出具体的皇后的摆法,只需要每次生成一种解法时,计数器加一即可,代码如下:
解法一:
class Solution {
public:
int totalNQueens(int n) {
int res = ;
vector<int> pos(n, -);
helper(pos, , res);
return res;
}
void helper(vector<int>& pos, int row, int& res) {
int n = pos.size();
if (row == n) ++res;
for (int col = ; col < n; ++col) {
if (isValid(pos, row, col)) {
pos[row] = col;
helper(pos, row + , res);
pos[row] = -;
}
}
}
bool isValid(vector<int>& pos, int row, int col) {
for (int i = ; i < row; ++i) {
if (col == pos[i] || abs(row - i) == abs(col - pos[i])) {
return false;
}
}
return true;
}
};
但是其实我们并不需要知道每一行皇后的具体位置,而只需要知道会不会产生冲突即可。对于每行要新加的位置,需要看跟之前的列,对角线,及逆对角线之间是否有冲突,所以我们需要三个布尔型数组,分别来记录之前的列 cols,对角线 diag,及逆对角线 anti_diag 上的位置,其中 cols 初始化大小为n,diag 和 anti_diag 均为 2n。列比较简单,是哪列就直接去 cols 中查找,而对角线的话,需要处理一下,如果我们仔细观察数组位置坐标的话,可以发现所有同一条主对角线的数,其纵坐标减去横坐标再加n,一定是相等的。同理,同一条逆对角线上的数字,其横纵坐标之和一定是相等的,根据这个,就可以快速判断主逆对角线上是否有冲突。任意一个有冲突的话,直接跳过当前位置,否则对于新位置,三个数组中对应位置都赋值为 true,然后对下一行调用递归,递归返回后记得还要还原状态,参见代码如下:
解法二:
class Solution {
public:
int totalNQueens(int n) {
int res = ;
vector<bool> cols(n), diag( * n), anti_diag( * n);
helper(n, , cols, diag, anti_diag, res);
return res;
}
void helper(int n, int row, vector<bool>& cols, vector<bool>& diag, vector<bool>& anti_diag, int& res) {
if (row == n) ++res;
for (int col = ; col < n; ++col) {
int idx1 = col - row + n, idx2 = col + row;
if (cols[col] || diag[idx1] || anti_diag[idx2]) continue;
cols[col] = diag[idx1] = anti_diag[idx2] = true;
helper(n, row + , cols, diag, anti_diag, res);
cols[col] = diag[idx1] = anti_diag[idx2] = false;
}
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/52
类似题目:
参考资料:
https://leetcode.com/problems/n-queens-ii/
https://leetcode.com/problems/n-queens-ii/discuss/20058/Accepted-Java-Solution
https://leetcode.com/problems/n-queens-ii/discuss/20048/Easiest-Java-Solution-(1ms-98.22)
LeetCode All in One 题目讲解汇总(持续更新中...)
[LeetCode] 52. N-Queens II N皇后问题之二的更多相关文章
- [Leetcode] n queens ii n皇后问题
Follow up for N-Queens problem. Now, instead outputting board configurations, return the total numbe ...
- [LeetCode] N-Queens II N皇后问题之二
Follow up for N-Queens problem. Now, instead outputting board configurations, return the total numbe ...
- lintcode 中等题:N Queens II N皇后问题 II
题目: N皇后问题 II 根据n皇后问题,现在返回n皇后不同的解决方案的数量而不是具体的放置布局. 样例 比如n=4,存在2种解决方案 解题: 和上一题差不多,这里只是求数量,这个题目定义全局变量,递 ...
- [LeetCode] Number of Islands II 岛屿的数量之二
A 2d grid map of m rows and n columns is initially filled with water. We may perform an addLand oper ...
- [LeetCode] 685. Redundant Connection II 冗余的连接之二
In this problem, a rooted tree is a directed graph such that, there is exactly one node (the root) f ...
- [LeetCode] Shortest Word Distance II 最短单词距离之二
This is a follow up of Shortest Word Distance. The only difference is now you are given the list of ...
- [LeetCode] Pascal's Triangle II 杨辉三角之二
Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3,Return [1,3, ...
- LeetCode 598. Range Addition II (范围加法之二)
Given an m * n matrix M initialized with all 0's and several update operations. Operations are repre ...
- LeetCode 59. Spiral Matrix II (螺旋矩阵之二)
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. For ...
随机推荐
- 我在生产项目里是如何使用Redis发布订阅的?(一)使用场景
转载请注明出处! 导语 Redis是我们很常用的一款nosql数据库产品,我们通常会用Redis来配合关系型数据库一起使用,弥补关系型数据库的不足. 其中,Redis的发布订阅功能也是它的一大亮点.虽 ...
- 使用NumPy、Numba的简单使用(二)
本来要写NLP第三课动态规划的,日了,写到一半发现自己也不会了,理论很简单,动态规划咋回事也知道,但是实现在源码上还是有点难度,现在简单给予题目描述,小伙伴也可以来思考一下,例题一,我们现在有1元硬币 ...
- Ubuntu关机重启后 NVIDIA-SMI 命令不能使用
问题: 电脑安装好Ubuntu系统后,后续安装了显卡驱动.CUDA.cuDNN等软件,后续一直没有关机.中间系统曾经有过升级,这也是问题所在.系统升级导致内核改变,并可能导致它与显卡驱动不再匹配,所以 ...
- 拥抱小程序,WeTest小程序全链路测试解决方案正式上线
背景 随着微信开放小程序开发功能,迅速在各个实体店抢占流量入口,广大商家看到了在线和离线的机会整合,利用小程序版本特点低成本进入市场,达到流量的获取和转化. 伴随着资本的进入,小程序开发市场也因此越来 ...
- 关于git回退版本的一点心得
我由于开发中不小心在master分支上开发,忘记了切换分支,最后我直接在master分支上提交,push,在开发分支上merge了master分支. 然后,同事告诉我他的代码要准备上线了,然而我的代码 ...
- vue学习指南:第一篇 - vue的介绍
三大主流框架: 1. Vue.js 是目前最火的一个前端框架,react是最流行的前端框架 (react除了开发网站,还可以开发手机app,Vue语法也是可以用于手机App开发的,需要借助于wexx) ...
- 项目进程中input的onblur事件挂不上去,失效问题解决记录
一开始直接在js文件中写 var n=document.querySelector("input"); n.onblur=funcition(){ ///事件过程吧啦啦啦 }; 事 ...
- docker研究-5 docker网络介绍
例子:启动(创建)一个容器,自定义容器名字为my_nginxtest02,镜像为nginx,将宿主机(本机)81端口映射到容器的80端口 [root@localhost ~]# docker run ...
- linux 使用indent格式化代码
indent是一个代码整理工具,能够方便快速的将代码格式化. 这是我较习惯的代码风格,网上还有很多其他的 参数: -nbad -bap -bbo -nbc -br -brs -c33 -cd33 -n ...
- 基于VLC库C#开发可播放摄像头及任意格式视频的播放器
前言 本文主要讲述,在WPF中,借助Vlc.DotNet调用VLC类库,实现视频播功能,下面我们先来做开发前的准备工作. 准备工作 首先,我们创建一个项目WpfVLC,然后,进入Neget搜索Vlc. ...