Leetcode | N-Queens I & II
N-Queens I
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 all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.
For example,
There exist two distinct solutions to the 4-queens puzzle:
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."], ["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
Wiki:任两个皇后都不能处于同一条横行、纵行或斜线上。八皇后问题可以推广为更一般的n皇后摆放问题:这时棋盘的大小变为n×n,而皇后个数也变成n。当且仅当 n = 1 或 n ≥ 4 时问题有解。
回溯,用了一个数组col[i]来表示第i列是不是已经放了queen。
对于(row1, col1)和(row2, col2)这两个位置,如果它们在同一对角线上,那么有abs(row1-row2) = abs(col1-col2)。
class Solution {
public:
vector<vector<string> > solveNQueens(int n) {
if (n == || n == ) {
return ret;
}
vector<string> sol(n, string(n, '.'));
vector<bool> col(n, false);
bt(n, , col, sol);
return ret;
}
void bt(int n, int r, vector<bool> &col, vector<string> &sol) {
if (r >= n) {
ret.push_back(sol);
return;
}
for (int i = ; i < n; ++i) {
if (col[i]) continue;
bool diag = false;
for (int j = r - ; j >= ; --j) {
for (int m = ; m < n; ++m) {
if (abs(j - r) == abs(m - i) && sol[j][m] == 'Q') {
diag = true;
break;
}
}
}
if (!diag) {
col[i] = true;
sol[r][i] = 'Q';
bt(n, r + , col, sol);
col[i] = false;
sol[r][i] = '.';
}
}
}
private:
vector<vector<string> > ret;
};
N-Queens II
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
和N-Queens I 类似,同样需要回溯。
前面回溯的时候需要用到一个额外的数组col[i],而且用到了sol这个数组来判断对角线元素。
网上的解决方案更巧妙些,用到一个数组sol[i],存的是第i行可解的列号。
当处理到第r行时,检查前r-1行,看sol[0...r-1]有没有等于i的,有就代表了该列已经有queen了。然后再检查对角线上的。
class Solution {
public:
int totalNQueens(int n) {
if (n == || n == ) {
return ;
}
vector<int> sol(n, -);
total = ;
bt(n, , sol);
return total;
}
void bt(int n, int r, vector<int> &sol) {
if (r >= n) {
total++;
return;
}
for (int i = ; i < n; ++i) {
bool valid = true;
for (int j = r - ; j >= ; --j) {
for (int m = ; m < n; ++m) {
if (sol[j] == i || abs(j - r) == abs(sol[j] - i)) {
valid = false;
break;
}
}
}
if (valid) {
int t = sol[r];
sol[r] = i;
bt(n, r + , sol);
sol[r] = t;
}
}
}
private:
int total;
};
第三次写,在返回值统计。至此leetcode三遍刷完。
class Solution {
public:
int totalNQueens(int n) {
if (n <= ) return ;
vector<int> colSetted(n, -);
return recurse(n, , colSetted);
}
int recurse(int n, int row, vector<int> &colSetted) {
if (row >= n) {
return ;
}
int count = ;
for (int i = ; i < n; ++i) {
if (colSetted[i] == -) {
bool couldSet = true;
for (int j = ; j < n; ++j) {
if (colSetted[j] != - && abs(row - colSetted[j]) == abs(i - j)) {
couldSet = false;
break;
}
}
if (couldSet) {
colSetted[i] = row;
count += recurse(n, row + , colSetted);
colSetted[i] = -;
}
}
}
return count;
}
};
Leetcode | N-Queens I & II的更多相关文章
- LeetCode Single Number I / II / III
[1]LeetCode 136 Single Number 题意:奇数个数,其中除了一个数只出现一次外,其他数都是成对出现,比如1,2,2,3,3...,求出该单个数. 解法:容易想到异或的性质,两个 ...
- [array] leetcode - 40. Combination Sum II - Medium
leetcode - 40. Combination Sum II - Medium descrition Given a collection of candidate numbers (C) an ...
- LeetCode 137. Single Number II(只出现一次的数字 II)
LeetCode 137. Single Number II(只出现一次的数字 II)
- LeetCode:路径总和II【113】
LeetCode:路径总和II[113] 题目描述 给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径. 说明: 叶子节点是指没有子节点的节点. 示例:给定如下二叉树, ...
- LeetCode:组合总数II【40】
LeetCode:组合总数II[40] 题目描述 给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合. candi ...
- [Leetcode] n queens ii n皇后问题
Follow up for N-Queens problem. Now, instead outputting board configurations, return the total numbe ...
- [Leetcode][Python]52: N-Queens II
# -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 52: N-Queens IIhttps://oj.leetcode.com/ ...
- [LeetCode] Number of Islands II 岛屿的数量之二
A 2d grid map of m rows and n columns is initially filled with water. We may perform an addLand oper ...
- LeetCode:Word Ladder I II
其他LeetCode题目欢迎访问:LeetCode结题报告索引 LeetCode:Word Ladder Given two words (start and end), and a dictiona ...
- LeetCode:Path Sum I II
LeetCode:Path Sum Given a binary tree and a sum, determine if the tree has a root-to-leaf path such ...
随机推荐
- 使用 TRegistry 类[1]: 显示各主键下的项
使用 TRegistry 类[1]: 显示各主键下的项 {XP 注册表中的主键} HKEY_CLASSES_ROOT {文件类型信息} HKEY_CURRENT_USER {当前用户信息} ...
- CodeForces - 427B (模拟题)
Prison Transfer Time Limit: 1000MS Memory Limit: 262144KB 64bit IO Format: %I64d & %I64u Sub ...
- Myeclipse中全部文件设置成UTF-8
如果要使插件开发应用能有更好的国际化支持,能够最大程度的支持中文输出,则最好使 Java文件使用UTF-8编码.然而,Eclipse工作空间(workspace)的缺省字符编码是操作系统缺省的编码,简 ...
- ubuntu下常用服务器的构建
1 ftp 1.1 ftp服务器 1.安装vsftpd服务器 sudo apt-get install vsftpd 2.配置vsftpd.conf文件 sudo vi /etc/vsftpd.con ...
- Zabbix报告无交换内存主机 Lack of free swap space on xxxxx
[root@xx ~]# free -m total used free shared buffers cached Mem: 3832 3488 343 0 267 2389 -/+ buffers ...
- JUC回顾之-AQS同步器的实现原理
1.什么是AQS? AQS的核心思想是基于volatile int state这样的volatile变量,配合Unsafe工具对其原子性的操作来实现对当前锁状态进行修改.同步器内部依赖一个FIFO的双 ...
- PhpStorm 配置Xdebug
IDE => Xdebug => Apache(XAMPP) => Firefox + easist Xdebug 1>XAMPP停止apache服务;2>在安装目录下找 ...
- oracle 10g 学习之基本 SQL SELECT 语句(4)
本篇文章中,对于有的和MSSQL Server相同的语法我就没有再写了,这里我只写Oracle和MSSQL Server有点不同的 定义空值 l 空值是无效的,未指定的,未知的或不可预知的值 l ...
- 使用ASP.NET 5开发AngularJS应用
今天推荐的是一个系列文章,讲述了如何使用ASP.NET 5来开发AngularJS应用,一共7篇文章. 在Visual Studio 2015中由于优化了项目结构,优化了前端JS框架的引用方式,所以开 ...
- C语言标量类型(转)
在C语言中,枚举类型.字符型和各种整数的表示形式统一叫做标量类型. 当在C表达式中使用标量类型的值时,编译器就会自动将这些标识符转换为整数保存. 这种机制的作用是,在这些标量类型上执行的操作与整型上执 ...