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.

题目

NxN棋盘摆N个棋子,要求不能同行、同列、同对角线、同反对角线,返回所有摆法。

思路

DFS: C[i] 表示第i行皇后所在的列编号,即在位置 (i, C[i])上放了一个皇后,这样用一个一维数组,就能记录整个棋盘。

代码

 /*
TIME: O(n!*n) n行*每行从n 到 n-1 到 n-2...1 即 n!
SPACE: O(n)
*/ class Solution {
public List<List<String>> solveNQueens(int n) {
List<List<String>> result = new ArrayList<>();
int[] C = new int[n]; // C[i]表示第i行皇后所在的列编号,从二维降到一维
dfs(C, 0, result);
return result;
}
private static void dfs(int[] C, int row, List<List<String>> result) {
int N = C.length;
if (row == N) { // 终止条件,也是收敛条件,意味着找到了一个可行解
List<String> solution = new ArrayList<>();
// 第i行
for (int i = 0; i < N; ++i) {
char[] charArray = new char[N];
Arrays.fill(charArray, '.');
//第j列
for (int j = 0; j < N; ++j) {
if (j == C[i]) charArray[j] = 'Q';
}
solution.add(new String(charArray));
}
result.add(solution);
return;
} for (int j = 0; j < N; ++j) { // 扩展状态,一列一列的试
boolean ok = isValid(C, row, j);
if (!ok) continue; // 剪枝,如果非法,继续尝试下一列
// 执行扩展动作
C[row] = j;
dfs(C, row + 1, result);
// 撤销动作
// C[row] = -1;
}
} /**
* 能否在 (row, col) 位置放一个皇后.
*
* @param C 棋局
* @param row 当前正在处理的行,前面的行都已经放了皇后了
* @param col 当前列
* @return 能否放一个皇后
*/
private static boolean isValid(int[] C, int row, int col) {
for (int i = 0; i < row; ++i) {
// 在同一列
if (C[i] == col) return false;
// 在同一对角线上
if (Math.abs(i - row) == Math.abs(C[i] - col)) return false;
}
return true;
}
}

[leetcode]51. N-QueensN皇后的更多相关文章

  1. [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 ...

  2. Java实现 LeetCode 51 N皇后

    51. N皇后 n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击. 上图为 8 皇后问题的一种解法. 给定一个整数 n,返回所有不同的 n 皇后问题的解决 ...

  3. leetcode 51. N皇后 及 52.N皇后 II

    51. N皇后 问题描述 n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击. 上图为 8 皇后问题的一种解法. 给定一个整数 n,返回所有不同的 n 皇后 ...

  4. LeetCode 51. N-QueensN皇后 (C++)(八皇后问题)

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

  5. leetcode 51 N皇后问题

    代码,由全排列转化而来,加上剪枝,整洁的代码: 共有4个变量,res(最终的结果),level,当前合理的解,n皇后的个数,visit,当前列是否放过皇后,由于本来就是在新的行方皇后,又通过visit ...

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

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

  7. LeetCode: 51. N-Queens(Medium)

    1. 原题链接 https://leetcode.com/problems/n-queens/description/ 2. 题目要求 游戏规则:当两个皇后位于同一条线上时(同一列.同一行.同一45度 ...

  8. leetcode刷题-52N皇后2

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

  9. LeetCode - 51. N-Queens

    51. N-Queens Problem's Link ------------------------------------------------------------------------ ...

随机推荐

  1. Django学习笔记之URL与视图

    视图 视图一般都写在app的views.py中.并且视图的第一个参数永远都是request(一个HttpRequest)对象.这个对象存储了这个http请求的所有信息,其中包括携带的参数以及一些头部信 ...

  2. myibatis的坑--text类型的字段查询缺失

    问题:某个字段的类型为text(或者mediumtext,longtext)的时候,用selectByQuery语句查询出来的结果不包含该字段内容. myibatis 用mybatis-generat ...

  3. Xilinx 7 series FPGA multiboot技术的使用

    Xilinx 7 series FPGA multiboot技术的使用 当升级程序有错误的时候,系统会启动golden bitstream 注意:需要在源工程与升级工程中添加如下约束语句 生成组合mc ...

  4. 【C++】vector内存机制和性能分析

    转自:https://blog.csdn.net/mfcing/article/details/8746256 一些好的公司校园招聘过程中(包括笔试.面试环节),经常会涉及到STL中vector的使用 ...

  5. 黄聪:谷歌验证 (Google Authenticator) 的实现原理是什么?

    著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处.作者:徐小花链接:http://www.zhihu.com/question/20462696/answer/18731073来源: ...

  6. TCP/IP学习20180629-数据链路层-ARP、IP

    1.数据链路层:IP.ARP.RARPARP协议用来找到目标主机的Ethernet网卡Mac地址,IP协议用来承载数据ARP协议找到目标,IP协议传输数据2.IP协议ip协议是TCP/IP协议的核心, ...

  7. 推导式_zip

    zip ''' 功能: 每次分别拿出一个iter内的元素, 配对组成元祖, 放入迭代器, 如果元素不够配对, 将舍弃后面的元素 参数:n个iterable 返回:迭代器 ''' # (1) 用zip形 ...

  8. Node安装及自定义config

    下载Node.js , Windows下安装一键到底, 没有什么说的. 主要是默认无法流畅使用, 包括流畅下载, 全局缓存之类. 如下是进一步设置, 包括: - 设置淘宝镜像. - 增加Yarn(np ...

  9. 谷歌浏览器内核Cef js代码整理(三) 字符串处理

    *字符串截取方法*/ var s="abc_def[ghi]jk[i]"; var temp;function CopyFromStr(str_source,str_key, bl ...

  10. ffmpeg 编译

    下载FFmpeg git clone https://git.ffmpeg.org/ffmpeg.git 配置编译FFmpeg ./configure --prefix=host --enable-s ...