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

类似题目:

N-Queens

参考资料:

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] N-Queens II N皇后问题之二的更多相关文章

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

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

  2. [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 ...

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

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

  4. [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 ...

  5. [leetcode]52. N-Queens II N皇后

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

  6. [LeetCode] Palindrome Permutation II 回文全排列之二

    Given a string s, return all the palindromic permutations (without duplicates) of it. Return an empt ...

  7. [LeetCode] Redundant Connection II 冗余的连接之二

    In this problem, a rooted tree is a directed graph such that, there is exactly one node (the root) f ...

  8. [LeetCode] Arithmetic Slices II - Subsequence 算数切片之二 - 子序列

    A sequence of numbers is called arithmetic if it consists of at least three elements and if the diff ...

  9. [LeetCode] Contains Duplicate II 包含重复值之二

    Given an array of integers and an integer k, return true if and only if there are two distinct indic ...

随机推荐

  1. 看我是如何处理自定义线程模型---java

    看过我之前文章的园友可能知道我是做游戏开发,我的很多思路和出发点是按照游戏思路来处理的,所以和web的话可能会有冲突,不相符合. 来说说为啥我要自定义线程模型呢? 按照我做的mmorpg或者mmoar ...

  2. 打造高效前端工作环境-tmuxinator

    前言  虽然tmux能让我们方便组织工作环境,但每次重新打开会话时都需要手动重新创建窗口.窗格和执行各种程序,能不能像VS那样以工程为单位保存窗口.窗格和各种所需执行的程序的信息呢?tmuxinato ...

  3. WebComponent魔法堂:深究Custom Element 之 标准构建

    前言  通过<WebComponent魔法堂:深究Custom Element 之 面向痛点编程>,我们明白到其实Custom Element并不是什么新东西,我们甚至可以在IE5.5上定 ...

  4. C# 本质论 第四章 方法和参数

    要为方法名使用动词或动词短语 递归:递归调用方法 方法重载: try catch

  5. 【原创】C#模拟Post请求,正文为json数据的代码参考

    由于之前一直在做键值对post数据的提交,没遇到过json正文的提交,遇到的问题截图: 对于此种情况的post,我用 谷歌插件 PostMan 模拟试了下成功了,截图如下: Postman插件在你选择 ...

  6. Java微信公众平台接口封装源码分享

    前言:      这篇博客是在三月初动手项目的时候准备写的,但是为了完成项目只好拖延时间写这篇博客,顺便也可以在项目中应用我自己总结的的一些经验.今天看来,这些方法的应用还是可以的,至少实现了我之前的 ...

  7. Python VS PHP 基础语法

    这几天在学习Python,鄙人平时学习中为了方便记忆和更好的比较与理解语言二者之间在某些情况的优劣性,所以花了点时间,整理了一下 Python 和 PHP 常用语法的一些区别. 一.大小写 PHP: ...

  8. Mac下安装ElasticSearch

    简单记录一下安装ES的过程,给小小白们提供一下参考: 下载安装包 https://www.elastic.co/downloads/elasticsearch建议下载2.3.2版本,最新的5.0.0版 ...

  9. Threejs中的材质贴图

    最近项目需要折腾three.js,有关three.js几点说明 1.作用 threejs适合创建简单的模型视图 2.对于复杂的模型图(如:室内模型图)需要美术3D制作,前端导成特定格式文件(如*.mt ...

  10. Github装(zao)逼(jia)指(da)南(fa)

    Github之于工程师,类似于微博相册之于嫩模,像是个门面. 无论是晋升答辩,还是求职面试,有一个丰富的代码仓库不敢说好处有多大,但总归是有的.并且好处不局限于此,代码开源才会暴露问题才会改正,并且会 ...