[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 ...
随机推荐
- storm整合kafka storm-kafka-client
pom.xml-注意jar-log4j---------------------<dependencies> <dependency> <groupId>org.a ...
- Android Binder机制彻底梳理一
Binder架构图: 先来瞅一下它的整体架构图: 其中粉红部分是上层的Binder,而蓝色的则是下层的Binder,很显然上层的是依赖于下层的. 什么是Binder[有个大概了解]? 这里从几个层面来 ...
- myslq数据库用union all查询出现 #1271 - Illegal mix of collations for operation 'UNION'
出现 #1271 - Illegal mix of collations for operation 'UNION' 的原因是两个字符编码不匹配造成的. 我遇到的是 utf8_general_ci ...
- jQuery 遍历 - 过滤
三个最基本的过滤方法是:first(), last() 和 eq(),它们允许您基于其在一组元素中的位置来选择一个特定的元素. 其他过滤方法,比如 filter() 和 not() 允许您选取匹配或不 ...
- Tortoise Git 安装 及报错处理
TortoiseGit安装详解: https://www.cnblogs.com/xinlj/p/5978730.html Tortoise Git 错误处理 disconnected no supp ...
- Spring源码窥探之:@Profile
Spring为我们提供的多环境启动 1. 配置类,注入三个不同环境的数据源,并加上注解 /** * description: 以下准备了三套不同环境的数据源 * * @author 70KG * @d ...
- Permission denied (publickey,gssapi-keyex,gssapi-with-mic).错误的解决
SSH登录提示 Permission denied (publickey,gssapi-keyex,gssapi-with-mic). 修改被登录的SSH服务器ssh配置,/etc/ssh/sshd_ ...
- SpringBoot之使用Druid连接池,SQL监控和spring监控
项目结构 1.引入maven依赖 <dependencies> <dependency> <groupId>org.springframework.boot< ...
- C++ socket bind() 函数绑定错误
VS2015编译错误: errorCxxxx: 'initializing' : cannot convert from 'std::_Bind<false,void,SOCKET&,s ...
- learning at command AT+CPIN
[Purpose] Learning how to check sim ready? [Eevironment] Shell terminal, base on gcom command and gc ...