[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 ...
随机推荐
- javascript中的发布订阅模式与观察者模式
这里了解一下JavaScript中的发布订阅模式和观察者模式,观察者模式是24种基础设计模式之一. 设计模式的背景 设计模式并非是软件开发的专业术语,实际上设计模式最早诞生于建筑学. 设计模式的定义是 ...
- 【UOJ#82】【UR #7】水题生成器(贪心)
[UOJ#82][UR #7]水题生成器(贪心) 题面 UOJ 题解 把\(n!\)的所有约数搜出来,这个个数不会很多. 然后从大往小能选则选就好了. #include<iostream> ...
- 【UOJ#60】【UR #5】怎样提高智商
[UOJ#60][UR #5]怎样提高智商 题面 UOJ 题解 首先猜猜答案是\(4*3^{n-1}\).即前面的选啥都行,后面的搞搞就行了. 而打表(看题解),可以知道答案就是这个,并且每个问题都是 ...
- keepalived+Nginx实现主备保障Nginx的高可用。
1.什么是keepalived? Keepalived是集群管理中保证集群高可用的一个服务软件,用来防止单点故障. Keepalived的作用是检测web服务器的状态,如果有一台web服务器死机,或工 ...
- laravel 广播细节讲解
1.应用场景 1.通知(Notification) 或 信号(Signal) 2.通知是最简单的示例,也最经常用到.信号也可看作是通知的一种展现形式,只不过信号没有UI而已. 3.Activity S ...
- 剑指 Offer——1. 二维数组中的查找
题目描述 在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序.请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数 ...
- 面试阿里百分百问的Jvm,别问有没有必要学,真的很有必要朋友
面试阿里百分百问的Jvm,别问有没有必要学,真的很有必要朋友 前言: JVM 的内存模型和 JVM 的垃圾回收机制一直是 Java 业内从业者绕不开的话题(实际调优.面试)JVM是java中很重要的一 ...
- delphi webbrowser用法集锦
delphi webbrowser用法集锦 (2012-05-13 08:29:00) 标签: it 分类: 软件_Software WebBrowser1.GoHome; //到浏览器默认主页 We ...
- vue--购物车案例(小知识点总结)
Html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF- ...
- 大学外语四六级英语词汇CET
anticipation n. 预期,期望 appreciation n. 感谢,感激 array n. 陈列,一系列 assurance n. 保证 emergency n. 紧急情况 encour ...