[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 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.."]
]
51. N-Queens N 的变形,这道题只需要给出不同解法的数量,比51题要简单一些。
解法:回溯Backtracking
Java:
/**
* don't need to actually place the queen,
* instead, for each row, try to place without violation on
* col/ diagonal1/ diagnol2.
* trick: to detect whether 2 positions sit on the same diagnol:
* if delta(col, row) equals, same diagnol1;
* if sum(col, row) equals, same diagnal2.
*/
private final Set<Integer> occupiedCols = new HashSet<Integer>();
private final Set<Integer> occupiedDiag1s = new HashSet<Integer>();
private final Set<Integer> occupiedDiag2s = new HashSet<Integer>();
public int totalNQueens(int n) {
return totalNQueensHelper(0, 0, n);
} private int totalNQueensHelper(int row, int count, int n) {
for (int col = 0; col < n; col++) {
if (occupiedCols.contains(col))
continue;
int diag1 = row - col;
if (occupiedDiag1s.contains(diag1))
continue;
int diag2 = row + col;
if (occupiedDiag2s.contains(diag2))
continue;
// we can now place a queen here
if (row == n-1)
count++;
else {
occupiedCols.add(col);
occupiedDiag1s.add(diag1);
occupiedDiag2s.add(diag2);
count = totalNQueensHelper(row+1, count, n);
// recover
occupiedCols.remove(col);
occupiedDiag1s.remove(diag1);
occupiedDiag2s.remove(diag2);
}
} return count;
}
Python:
# quick solution for checking if it is diagonally legal
class Solution:
# @return an integer
def totalNQueens(self, n):
self.cols = [False] * n
self.main_diag = [False] * (2 * n)
self.anti_diag = [False] * (2 * n)
return self.totalNQueensRecu([], 0, n) def totalNQueensRecu(self, solution, row, n):
if row == n:
return 1
result = 0
for i in xrange(n):
if not self.cols[i] and not self.main_diag[row + i] and not self.anti_diag[row - i + n]:
self.cols[i] = self.main_diag[row + i] = self.anti_diag[row - i + n] = True
result += self.totalNQueensRecu(solution + [i], row + 1, n)
self.cols[i] = self.main_diag[row + i] = self.anti_diag[row - i + n] = False
return result
Python:
# slower solution
class Solution:
# @return an integer
def totalNQueens(self, n):
return self.totalNQueensRecu([], 0, n) def totalNQueensRecu(self, solution, row, n):
if row == n:
return 1
result = 0
for i in xrange(n):
if i not in solution and reduce(lambda acc, j: abs(row - j) != abs(i - solution[j]) and acc, xrange(len(solution)), True):
result += self.totalNQueensRecu(solution + [i], row + 1, n)
return result
C++:
class Solution {
public:
int totalNQueens(int n) {
int res = 0;
vector<int> pos(n, -1);
totalNQueensDFS(pos, 0, res);
return res;
}
void totalNQueensDFS(vector<int> &pos, int row, int &res) {
int n = pos.size();
if (row == n) ++res;
else {
for (int col = 0; col < n; ++col) {
if (isValid(pos, row, col)) {
pos[row] = col;
totalNQueensDFS(pos, row + 1, res);
pos[row] = -1;
}
}
}
}
bool isValid(vector<int> &pos, int row, int col) {
for (int i = 0; i < row; ++i) {
if (col == pos[i] || abs(row - i) == abs(col - pos[i])) {
return false;
}
}
return true;
}
};
类似题目:
All LeetCode Questions List 题目汇总
[LeetCode] 52. N-Queens II N皇后问题 II的更多相关文章
- lintcode 中等题:N Queens II N皇后问题 II
题目: N皇后问题 II 根据n皇后问题,现在返回n皇后不同的解决方案的数量而不是具体的放置布局. 样例 比如n=4,存在2种解决方案 解题: 和上一题差不多,这里只是求数量,这个题目定义全局变量,递 ...
- Java实现 LeetCode 52 N皇后 II
52. N皇后 II n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击. 上图为 8 皇后问题的一种解法. 给定一个整数 n,返回 n 皇后不同的解决方案 ...
- lintcode-34-N皇后问题 II
34-N皇后问题 II 根据n皇后问题,现在返回n皇后不同的解决方案的数量而不是具体的放置布局. 样例 比如n=4,存在2种解决方案 标签 递归 思路 参考http://www.cnblogs.com ...
- Leetcode 137. 只出现一次的数字 II - 题解
Leetcode 137. 只出现一次的数字 II - 题解 137. Single Number II 在线提交: https://leetcode.com/problems/single-numb ...
- [Leetcode 90]求含有重复数的子集 Subset II
[题目] Given a collection of integers that might contain duplicates, nums, return all possible subsets ...
- Leetcode之二分法专题-167. 两数之和 II - 输入有序数组(Two Sum II - Input array is sorted)
Leetcode之二分法专题-167. 两数之和 II - 输入有序数组(Two Sum II - Input array is sorted) 给定一个已按照升序排列 的有序数组,找到两个数使得它们 ...
- Leetcode之回溯法专题-212. 单词搜索 II(Word Search II)
Leetcode之回溯法专题-212. 单词搜索 II(Word Search II) 给定一个二维网格 board 和一个字典中的单词列表 words,找出所有同时在二维网格和字典中出现的单词. 单 ...
- Leetcode之回溯法专题-40. 组合总和 II(Combination Sum II)
Leetcode之回溯法专题-40. 组合总和 II(Combination Sum II) 给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使 ...
- Leetcode之动态规划(DP)专题-264. 丑数 II(Ugly Number II)
Leetcode之动态规划(DP)专题-264. 丑数 II(Ugly Number II) 编写一个程序,找出第 n 个丑数. 丑数就是只包含质因数 2, 3, 5 的正整数. 示例: 输入: n ...
随机推荐
- 路由器安全——破解wifi密码,同时中间人攻击
聊聊安全那些事儿 篇一:Wi-Fi安全浅析 2016-04-25 13:18:16 141点赞 712收藏 63评论 前言 近期,Wi-Fi相关的安全话题充斥着电视新闻的大屏幕,先是曝出了路由器劫持的 ...
- anyproxy学习4-Linux(Centos)搭建anyproxy环境
前言 anyproxy可以跨平台使用,前面第一篇是搭建在windows机器上,本篇讲如何在linux上搭建anyproxy环境,当然有mac的小伙伴也可以用mac去搭建一个环境. nodejs安装 a ...
- vue 弹框
弹框展示: 代码: <template> <div> <el-col :span="9" style="text-align: right; ...
- 【CLAA系列】CLAA 通讯过程
名词: MSP:中兴服务器 CS:客户服务器,也就是我们的服务器 GW:网关,这里默认是中兴的网关 Chip:芯片,这里特指包含了Lora标准通讯模块,且针对CLAA做过特殊优化的芯片. Lora:L ...
- Linux——CentOS7没有ifconfig命令
前言 今天新安装的centos7,使用ifconfig命令却提示没有,直接安装也没有~ 正文 直接安装直接告诉我这个包不是一个有效的 [root@kafka ~]# yum install -y if ...
- postgres常用运维sql
1.查看数据库大小 select pg_database_size('log_analysis'); postgres=# select pg_database_size('postExpress') ...
- web自动化测试-selenium多表单切换
一.概述 1.在web应用中会经常遇到frame/iframe表单嵌套页面的应用 2.WebDriver只能在一个页面上对元素进行识别与定位 3.对于frame/iframe表单内嵌的页面上元素无法识 ...
- SpringMVC_原理(转)
在整个Spring MVC框架中,DispatcherServlet处于核心位置,它负责协调和组织不同组件完成请求处理并返回响应的工作.具体流程为:1)客户端发送http请求,web应用服务器接收到这 ...
- qtcreator cannot find catkin packages
adding /opt/ros/kinetic to CMAKE_PREFIX_PATH in Project -> build environment only /opt/ros/kineti ...
- linux学习8 运维基本功-Linux获取命令使用帮助详解
一.Linux基础知识 1.人机交互界面: a.GUI b.CLI:[login@hostname workdir]# COMMAND 2.命令知识 通用格式:# COMMAND OPTIONS A ...