题目

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:

分析

一个经典N皇后问题,这种棋盘类的题目一般是回溯法, 依次放置每行的皇后。要求在放置的时候,要保持当前的状态为合法,即当前放置位置的同一行、同一列、两条对角线上都不存在皇后。

多种解法请参考

AC代码


  1. class Solution {
  2. private:
  3. vector<vector<string> > ret;
  4. public:
  5. vector<vector<string>> solveNQueens(int n) {
  6. if (n <= 0)
  7. return vector<vector<string>>();
  8. //二维字符矩阵,存储当前满足N皇后的解
  9. vector<string> cur(n, string(n, '.'));
  10. //调用主函数
  11. set_queens(cur, 0);
  12. return ret;
  13. }
  14. void set_queens(vector<string> &cur, int row)
  15. {
  16. int size = cur.size();
  17. if (row == size)
  18. {
  19. ret.push_back(cur);
  20. return;
  21. }
  22. else{
  23. for (int col = 0; col < size; col++)
  24. {
  25. if (isValid(cur, row, col))
  26. {
  27. cur[row][col] = 'Q';
  28. //安置下一个皇后
  29. set_queens(cur, row + 1);
  30. cur[row][col] = '.';
  31. }//for
  32. }//for
  33. }
  34. }
  35. //判断在cur[row][col]位置放一个皇后,是否是合法的状态
  36. //已经保证了每行一个皇后,只需要判断列是否合法以及对角线是否合法。
  37. bool isValid(vector<string> &cur, int row, int col)
  38. {
  39. //判断是否同列
  40. for (int i = 0; i < row; i++)
  41. {
  42. if (cur[i][col] == 'Q')
  43. return false;
  44. }//for
  45. //判断是否同一左对角线
  46. for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; --i, --j)
  47. {
  48. if (cur[i][j] == 'Q')
  49. return false;
  50. }
  51. //判断是否同一右对角线
  52. for (int i = row - 1, j = col + 1; i >= 0 && j <= cur.size(); --i, ++j)
  53. {
  54. if (cur[i][j] == 'Q')
  55. return false;
  56. }
  57. return true;
  58. }
  59. };

GitHub测试程序源码

LeetCode(51) N-Queens的更多相关文章

  1. LeetCode(51):N皇后

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

  2. Qt 学习之路 2(51):布尔表达式树模型

    Qt 学习之路 2(51):布尔表达式树模型 豆子 2013年5月15日 Qt 学习之路 2 17条评论 本章将会是自定义模型的最后一部分.原本打算结束这部分内容,不过实在不忍心放弃这个示例.来自于 ...

  3. LeetCode(275)H-Index II

    题目 Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimi ...

  4. LeetCode(220) Contains Duplicate III

    题目 Given an array of integers, find out whether there are two distinct indices i and j in the array ...

  5. LeetCode(154) Find Minimum in Rotated Sorted Array II

    题目 Follow up for "Find Minimum in Rotated Sorted Array": What if duplicates are allowed? W ...

  6. LeetCode(122) Best Time to Buy and Sell Stock II

    题目 Say you have an array for which the ith element is the price of a given stock on day i. Design an ...

  7. LeetCode(116) Populating Next Right Pointers in Each Node

    题目 Given a binary tree struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode * ...

  8. LeetCode(113) Path Sum II

    题目 Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given ...

  9. LeetCode(107) Binary Tree Level Order Traversal II

    题目 Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from l ...

随机推荐

  1. 分布式集群环境下,如何实现session共享三(环境搭建)

    这是分布式集群环境下,如何实现session共享系列的第三篇.在上一篇:分布式集群环境下,如何实现session共享二(项目开发)中,准备好了一个通过原生态的servlet操作session的案例.本 ...

  2. split("\\.")是什么意思

    \\会转义成反斜杠,反斜杠本身就是转义符,所有就成了“\.”,在进行转义就是.,所以\\.实际上是“.”.在java.lang包中也有String.split()方法,与.net的类似,都是返回是一个 ...

  3. AtCoder Grand Contest 003 F - Fraction of Fractal

    题目传送门:https://agc003.contest.atcoder.jp/tasks/agc003_f 题目大意: 给定一个\(H×W\)的黑白网格,保证黑格四连通且至少有一个黑格 定义分形如下 ...

  4. 136 Single Number 数组中除一个数外其他数都出现两次,找出只出现一次的数

    给定一个整数数组,除了某个元素外其余元素均出现两次.请找出这个只出现一次的元素.备注:你的算法应该是一个线性时间复杂度. 你可以不用额外空间来实现它吗? 详见:https://leetcode.com ...

  5. MyBatis学习(四)

    前言 最近比较松懈,下班回家后也懒得学习了.今晚实在是看不下去了,争取时间学习.社会上有这么多的资源,就看谁能抢的多吧.今天就说说MyBatis的动态SQL吧 正文 动态 SQL 通常要做的事情是有条 ...

  6. ETH Dapp 体验报告

    Dapp 体验报告 Dapp是分散式的应用程序.DApp运行在去中心化的网络上,也就是区块链网络中.网络中不存在中心化的节点可以完整的控制DApp. 必须依赖合约部署,没有一个中心化的服务器托管. 对 ...

  7. javascript动态添加、修改、删除对象的属性与方法

    在其他语言中,对象一旦生成,就不可更改了,要为一个对象添加修改成员必须要在对应的类中修改,并重新实例化,而且程序必须经过重新编译.JavaScript 中却非如此,它提供了灵活的机制来修改对象的行为, ...

  8. 【OpenCV】motion blur 的简单实现

    先推荐界面比较丑,但是还不错的在线图片处理网站: http://www168.lunapic.com/editor/ 由于最近在做毕设了,结合前面关于图像处理和机器学习的操作,想做一些好玩的东西,其中 ...

  9. 世平信息(W 笔试)

    选择题 大题 1.启动Thread的方法有几种 算法题 1.写出冒泡排序算法

  10. CAD交互绘制带周长面积的矩形框(网页版)

    主要用到函数说明: _DMxDrawX::DrawLine 绘制一个直线.详细说明如下: 参数 说明 DOUBLE dX1 直线的开始点x坐标 DOUBLE dY1 直线的开始点y坐标 DOUBLE ...