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. TCP四种计时器

    TCP共使用以下四种计时器,即重传计时器.坚持计时器.保活计时器和时间等待计时器 .这几个计时器的主要特点如下:      1.重传计时器      当TCP发送报文段时,就创建该特定报文段的重传计时 ...

  2. ASP.NET Core 中文文档 第四章 MVC(3.4)如何使用表单

    原文:Working with Forms 作者:Rick Anderson.Dave Paquette.Jerrie Pelser 翻译:姚阿勇(Dr.Yao) 校对:孟帅洋(书缘) 这篇文章演示了 ...

  3. IDEA上安装和使用checkstyle,findbugs,visualVM,PMD插件

    ##安装插件步骤: 1.打开settings 2.选择plugins 3.点击"Browse repositories" 4.搜索对应内插件,点击"install&quo ...

  4. JavaScript原型OOP——你上车了吗?

    .title-bar { width: 80%; height: 35px; padding-left: 35px; color: white; line-height: 35px; font-siz ...

  5. 使用Adminlite + ASP.NET MVC5(C#) + Entityframework + AutoFac + AutoMapper写了个api接口文档管理系统

    一.演示: 接口查看:http://apidoc.docode.top/ 接口后台:http://apiadmin.docode.top/ 登录:administrator,123456 二.使用到的 ...

  6. Devexpress GridControl.Export

    private void mnuExportTable_ItemClick_1(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { u ...

  7. FastSocket学习笔记~再说客户端与服务端的组成

    废话多说 很久之前,我写过几篇FastSocket的文章,基本属于使用的方法,而缺乏对概念的总结讲解,而本讲就是弥补一下上几讲的不足,将核心的模块再说说,再谈谈,再聊聊! 首先FastSocket由C ...

  8. macOS 升级到了10.12.1

    除了明面上的一些更新,但我感觉最重要的是触摸板的行为特征又还原了.

  9. 案例借鉴 | 某通讯巨头的IT建设方案

    成都联通作为合并重组后的中国联通在成都的分支机构,拥有基础扎实的通信网络和当前最先进技术的WCDMA网络.随着3G和4G业务的发展领先,成都联通凭借其出色的网络能力和服务,在用户中赢得了口碑. 在IT ...

  10. iOS:GCD理解1(同步-异步、串行-并行)

    1.并行-异步(ST1与ST2抢占资源) 1-1).获取 并行(全局)队列 ,DISPATCH_QUEUE_PRIORITY_DEFAULT 为默认优先级. dispatch_queue_t queu ...