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.

Example:

Input: 4
Output: [
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."], ["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.

经典的N皇后问题,基本所有的算法书中都会包含的问题。可能有些人对国际象棋不太熟悉,大家都知道中国象棋中最叼的是车,横竖都能走,但是在国际象棋中还有更叼的,就是皇后,不但能横竖走,还能走两个斜线,有如 bug 一般的存在。所以经典的八皇后问题就应运而生了,在一个 8x8 大小的棋盘上如果才能放8个皇后,使得两两之间不能相遇,所谓一山不能容二虎,而这里有八个母老虎,互相都不能相遇。对于这类问题,没有太简便的方法,只能使用穷举法,就是尝试所有的组合,每放置一个新的皇后的时候,必须要保证跟之前的所有皇后不能冲突,若发生了冲突,说明当前位置不能放,要重新找地方,这个逻辑非常适合用递归来做。我们先建立一个长度为 nxn 的全是点的数组 queens,然后从第0行开始调用递归。在递归函数中,我们首先判断当前行数是否已经为n,是的话,说明所有的皇后都已经成功放置好了,所以我们只要将 queens 数组加入结果 res 中即可。否则的话,我们遍历该行的所有列的位置,行跟列的位置都确定后,我们要验证当前位置是否会产生冲突,那么就需要使用一个子函数来判断了,首先验证该列是否有冲突,就遍历之前的所有行,若某一行相同列也有皇后,则冲突返回false;再验证两个对角线是否冲突,就是一些坐标转换,主要不要写错了,若都没有冲突,则说明该位置可以放皇后,放了新皇后之后,再对下一行调用递归即可,注意递归结束之后要返回状态,参见代码如下:

解法一:

class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> res;
vector<string> queens(n, string(n, '.'));
helper(, queens, res);
return res;
}
void helper(int curRow, vector<string>& queens, vector<vector<string>>& res) {
int n = queens.size();
if (curRow == n) {
res.push_back(queens);
return;
}
for (int i = ; i < n; ++i) {
if (isValid(queens, curRow, i)) {
queens[curRow][i] = 'Q';
helper(curRow + , queens, res);
queens[curRow][i] = '.';
}
}
}
bool isValid(vector<string>& queens, int row, int col) {
for (int i = ; i < row; ++i) {
if (queens[i][col] == 'Q') return false;
}
for (int i = row - , j = col - ; i >= && j >= ; --i, --j) {
if (queens[i][j] == 'Q') return false;
}
for (int i = row - , j = col + ; i >= && j < queens.size(); --i, ++j) {
if (queens[i][j] == 'Q') return false;
}
return true;
}
};

我们还可以只使用一个一维数组 queenCol 来保存所有皇后的列位置,初始化均为-1, 那么 queenCol[i] 就是表示第i个皇后在 (i, queenCol[i]) 位置,递归函数还是跟上面的解法相同,就是在当前行数等于n的时候,我们要将 queenCol 还原成一个 nxn 大小的矩阵,并存入结果 res 中。这种记录每个皇后的坐标的方法在验证冲突的时候比较简单,只要从第0行遍历到当前行,若跟之前的皇后的列数相同,直接返回false,叼就叼在判断对角线冲突非常简便,因为当两个点在同一条对角线上,那么二者的横坐标差的绝对值等于纵坐标差的绝对值,利用这条性质,可以快速的判断冲突,代码如下:

解法二:

class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> res;
vector<int> queenCol(n, -);
helper(, queenCol, res);
return res;
}
void helper(int curRow, vector<int>& queenCol, vector<vector<string>>& res) {
int n = queenCol.size();
if (curRow == n) {
vector<string> out(n, string(n, '.'));
for (int i = ; i < n; ++i) {
out[i][queenCol[i]] = 'Q';
}
res.push_back(out);
return;
}
for (int i = ; i < n; ++i) {
if (isValid(queenCol, curRow, i)) {
queenCol[curRow] = i;
helper(curRow + , queenCol, res);
queenCol[curRow] = -;
}
}
}
bool isValid(vector<int>& queenCol, int row, int col) {
for (int i = ; i < row; ++i) {
if (col == queenCol[i] || abs(row - i) == abs(col - queenCol[i])) return false;
}
return true;
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/51

类似题目:

N-Queens II

Grid Illumination

参考资料:

https://leetcode.com/problems/n-queens/

http://www.cnblogs.com/TenosDoIt/p/3801621.html

https://leetcode.com/problems/n-queens/discuss/19805/My-easy-understanding-Java-Solution

https://leetcode.com/problems/n-queens/discuss/19808/Accepted-4ms-c%2B%2B-solution-use-backtracking-and-bitmask-easy-understand.

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] N-Queens N皇后问题的更多相关文章

  1. [Leetcode] n queens ii n皇后问题

    Follow up for N-Queens problem. Now, instead outputting board configurations, return the total numbe ...

  2. [LeetCode] N-Queens II N皇后问题之二

    Follow up for N-Queens problem. Now, instead outputting board configurations, return the total numbe ...

  3. [CareerCup] 9.9 Eight Queens 八皇后问题

    9.9 Write an algorithm to print all ways of arranging eight queens on an 8x8 chess board so that non ...

  4. [LeetCode] 51. N-Queens N皇后问题

    The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens ...

  5. lintcode 中等题:N Queens N皇后问题

    题目: N皇后问题 n皇后问题是将n个皇后放置在n*n的棋盘上,皇后彼此之间不能相互攻击.<不同行,不同列,不同对角线> 给定一个整数n,返回所有不同的n皇后问题的解决方案. 每个解决方案 ...

  6. Python----递归------Eight Queens 八皇后问题

    递归思想是算法编程中的重要思想. 作为初学者,对递归编程表示很蒙逼,每次遇到需要递归的问题,心里就有一万头草泥马飞过~~~~~~(此处略去一万头草泥马) 在B站看数据结构与算法的视频时,视频中给了两个 ...

  7. Aizu - ALDS1_13_A-8 Queens Problem-八皇后的路径输出

    The goal of Queens Problem is to put eight queens on a chess-board such that none of them threatens ...

  8. leetcode刷题-52N皇后2

    题目 n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击.给定一个整数 n,返回 n 皇后不同的解决方案的数量. 思路 与51题完全一致 实现 class ...

  9. leetcode刷题-51N皇后

    题目 n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击. 给定一个整数 n,返回所有不同的 n 皇后问题的解决方案. 每一种解法包含一个明确的 n 皇后问 ...

  10. [LeetCode] N皇后问题

    LeetCode上面关于N皇后有两道题目:51 N-Queens:https://leetcode.com/problems/n-queens/description/ 52 N-Queens II: ...

随机推荐

  1. 执行插入语句,object val = cmd.ExecuteScalar() val = null

    在写接口的过程中遇到错误:空对象不能转换为值类型 因为我们使用的是petapoco,经过调试后发现是 object val = cmd.ExecuteScalar() 这一句造成的报错, val = ...

  2. Lenovo K29 笔记本经常没声音解决方案Hotkey[gevu18ww].exe

    下载 win8 快捷键驱动 安装即可解决 http://driverdl.lenovo.com.cn/lenovo/DriverFilesUploadFloder/36265/Hotkey[gevu1 ...

  3. 创建虚拟目录失败,必须为服务器名称指定“localhost”?看进来!!

    没废话,直接讲! 关于微信开发过程,远程调试后,再次打开vs出现项目加载失败的解决办法! 上图: 这图应该不陌生,你肯定打开iis把绑定的域名给干掉了.这个提示很坑人,简直就是坑爹!!!fck!! 来 ...

  4. Android Studio同时打开多个项目

    Android Studio的默认设置是打开第二个项目时,第一个项目就被自动关闭了,如果要同时打开多个项目,可以点击File->Settings,对Project Opening进行下面的设置: ...

  5. [函數] Firemonkey Android 取得系统参数设定的字型大小

    Android 系统参数设定内,可以设定字型大小: 可以透过下面代码来取得字型大小比例: function FontScale: Single; var Resources: JResources; ...

  6. C3p0连接池配置

    在Java开发中,使用JDBC操作数据库的四个步骤如下:   ①加载数据库驱动程序(Class.forName("数据库驱动类");)   ②连接数据库(Connection co ...

  7. 类型转换和类型相关函数.png

  8. 业务人员自助BI分析不够用,还要自助数据准备?

    自助式BI工具,可以帮助业务人员充分了解和利用企业数据,通过可视化操作,拖拖拽拽来新建分析,生成可视化的报表,帮助企业决策.但近几年的调查研究发现,拥有强大分析策略和模型的产品,比如Tableau.q ...

  9. Hadoop学习日志- install hadoop

    资料来源 : http://www.tutorialspoint.com/hadoop/hadoop_enviornment_setup.htm Hadoop 安装 创建新用户 $ su passwo ...

  10. [转]ASP.NET应用程序生命周期趣谈(五) IIS7瞎说

    Ps:建议初学者在阅读本文之前,先简要了解一下之前的几篇文章,以便于熟悉本文提到的一些关于IIS6的内容,方便理解.仅供参考. PS:为什么叫瞎说呢?我觉得自己理解的并不到位,只能是作为一个传声筒,希 ...