[LeetCode] 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] 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] 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 ...
- lintcode 中等题:N Queens II N皇后问题 II
题目: N皇后问题 II 根据n皇后问题,现在返回n皇后不同的解决方案的数量而不是具体的放置布局. 样例 比如n=4,存在2种解决方案 解题: 和上一题差不多,这里只是求数量,这个题目定义全局变量,递 ...
- [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 ...
- [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 ...
- [LeetCode] Palindrome Permutation II 回文全排列之二
Given a string s, return all the palindromic permutations (without duplicates) of it. Return an empt ...
- [LeetCode] Redundant Connection II 冗余的连接之二
In this problem, a rooted tree is a directed graph such that, there is exactly one node (the root) f ...
- [LeetCode] Arithmetic Slices II - Subsequence 算数切片之二 - 子序列
A sequence of numbers is called arithmetic if it consists of at least three elements and if the diff ...
- [LeetCode] Contains Duplicate II 包含重复值之二
Given an array of integers and an integer k, return true if and only if there are two distinct indic ...
随机推荐
- Java进击C#——应用开发之Asp.net
本章简言 上一章中笔者讲到关于Linq和EF的用法.并以hibernate来进行讲解.那么本章笔者来讲一下C#的Asp.Net.即是在B/S模式下开发.现在企业大部分的业务都是面向B/S模式的.所以对 ...
- 虚拟机安装CentOS6.4
1 概述 虚拟机(Virtual Machine)指通过软件模拟的具有完整硬件系统功能的.运行在一个完全隔离环境中的完整计算机系统,运行在主机上,完全独立,虚拟机里面的所有操作不会影响主机,即使虚拟 ...
- sql 补齐字段位数
select top 100 lmdte, right(replicate('0',6)+ltrim(lmtme),6) from smtpdsum where lmdte <> 0
- java获取https网站证书,附带调用https:webservice接口
一.java 获取https网站证书: 1.创建一个java工程,新建InstallCert类,将以下代码复制进去 package com; import java.io.BufferedReader ...
- 《连载 | 物联网框架ServerSuperIO教程》- 3.设备驱动介绍
1.C#跨平台物联网通讯框架ServerSuperIO(SSIO)介绍 <连载 | 物联网框架ServerSuperIO教程>1.4种通讯模式机制. <连载 | 物联网框架Serve ...
- jdk顺序表笔记
一.AbstractCollection 提供了集合的最大实现 继承该类,必须实现size()和iterator(),因为该类操作集合都是通过iterator 二.fail-fast策略 该策略在集合 ...
- springmvc+spring+mybatis+maven项目集成shiro进行用户权限控制【转】
项目结构: 1.maven项目的pom中引入shiro所需的jar包依赖关系 ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 ...
- LightGallery.js – 功能齐全的 Javascript Lightbox
Lightgallery是一个轻量级的模块化.响应式的灯箱画廊,它允许您创建美丽的图像和视频画廊.借助缩略图插件的帮助,Lightgallery 允许您创建缩略图画廊.它支持触摸屏设备上滑动导航以及桌 ...
- 纯css3 3D图片立方体旋转动画特效
纯css3 3D立方体模块,鼠标触碰,模块炸开,大立方体中套小立方体 效果展示 手机扫描二维码体验效果: 效果图如下: 源码下载:http://hovertree.com/h/bjaf/0qmul8g ...
- 利用NetworkExtension库配置VPN
VPN简单说就是连接局域网的一个通道.Ios8之后苹果增加了一个VPN的接口NEVPNManager,它可以方便的添加VPN连接. 首先在你的Xcode内,TARGETS->Capabiliti ...