[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 ...
随机推荐
- appium+python自动化63-使用Uiautomator2报错问题解决
前言 appium desktop V1.7.1版本使用命令行版本启动appium后,使用Uiautomator2定位toast信息报错:appium-uiautomator2-server-v0.3 ...
- linux Crontab定时备份项目案例
首先先写好备份的脚本(拷贝的命令) #bash/bin cd /finance/tomcat8-finance/wtpwebapps tar -czf /finance/webapp_backup/* ...
- c#3.0 Lambda 表达式
使用c# 2.0 中的匿名方法查找“内部包含abc子串的所有字符串”: list.FindAll( delegate(string s) { renturn s.indexof("abc&q ...
- windows 10 下使用Navicat for oracle 数据库还原
一.前期准备 1.安装windows 10系统 2.安装oracle 11g 数据库 3.安装PLsql(也不需要) 4.安装sqlplus(这个必须有) 5.使用下面这个东西新建数据库(不懂创建的话 ...
- rs485一主多从的连接方式及通信注意事项
rs485的通信方式看似比较简单,其实通信软件的处理还是有需要注意的. 下图是主机向从机发送信息的示意图,其中485的线都是手牵手相连的,因此主机向下发的时候,其实各个从机都有在接收数据的,只是,从机 ...
- 代码中的mysql语法问题
今天在代码中写了mysql的删除语句 String lpinsuredSQL=" delete from lpinsured a where a.insuredid='?InsuredID? ...
- navicat 远程连接服务器1130,1045问题报错处理
本人踩坑多次,一开始网上搜罗,解决办法大同小异,摸索了很久才全部解决完成,小小bug真磨人啊 首先,根据我的踩坑记录,navicat 1045和navicat 1130貌似属于同一种解决方案,都是修改 ...
- 14.go内置的rate包学习2(有花操作,必看)
package main import ( "fmt" "golang.org/x/time/rate" "time" ) func mai ...
- SIGAI机器学习第二十四集 聚类算法1
讲授聚类算法的基本概念,算法的分类,层次聚类,K均值算法,EM算法,DBSCAN算法,OPTICS算法,mean shift算法,谱聚类算法,实际应用. 大纲: 聚类问题简介聚类算法的分类层次聚类算法 ...
- Linux 字符集的查看及修改
一·查看字符集 字符集在系统中体现形式是一个环境变量,以CentOS6.5为例,其查看当前终端使用字符集的方式可以有以下几种方式: 第一种: [root@Testa-www tmp]# echo $L ...