笔试题65. LeetCode OJ (52)
来源:互联网 发布:lnmp nginx配置文件 编辑:程序博客网 时间:2024/05/18 00:43
这个题的意思是让我们求“n 后问题”的解法的数目,其实和上一个题基本是相似的,只需要做少量的改动就行,主要的思路如下:
1.使用 vector<string> 保存每一层的Queen的位置,然后往下一层递归,测试下一层Queen的位置,若符合要求就继续上下测试,若不符合则更换位置继续测试。
2.测试函数的编写需要注意,记得斜线上的点的测试,假设我们先将Queen置于中心上,那么该点的左右,上下,以及左上方和右下方,左下方和右上方等等都需要考虑到,不要漏掉任何一点,而且需要考虑边界问题。
3.在程序中我们应该提前检测,意思就是不要递归到最后一层才检查当前方案是否合格,我们在每一层的每个位置都需要检查是否合格,这样可以提前做出决策,这样可以大大减少递归的次数,提高程序的效率。
下面我就给出代码:
class Solution {public:int totalNQueens(int n){int ret = 0;vector<string> oneSolve;oneSolve.clear();for (int i = 0; i < n; ++i){string tmp(n, '.');oneSolve.push_back(tmp);}_solves(ret,oneSolve, n, 0);return ret;}void _solves(int &ret,vector<string> oneSolve, int n, int index){if (index == n){++ret;return;}for (int i = 0; i < n; ++i){oneSolve[index][i] = 'Q';if (!_testQueen(oneSolve, index + 1, n)){//检查当前行,提前做出决策oneSolve[index][i] = '.';continue;}_solves(ret, oneSolve, n, index + 1);oneSolve[index][i] = '.';}}bool _testQueen(vector<string>& tmp, int m, int n){ // m行,n列(m可能小于n)int i = m - 1;int j = 0;for (; j < n; ++j){if (tmp[i][j] == 'Q'){break;}}// tmp[i][j] == 'Q'// 检查行for (int k = j + 1; k < n; ++k){if (tmp[i][k] == 'Q'){return false;}}//检查列for (int k = 0; k < i; ++k){if (tmp[k][j] == 'Q'){return false;}}for (int k = i + 1; k < m; ++k){if (tmp[k][j] == 'Q'){return false;}}//检查斜线上的//左上int beginx = i;int beginy = j;while (beginx > 0 && beginy > 0){//if (tmp[--beginx][--beginy] == 'Q'){return false;}}//右下beginx = i;beginy = j;while (beginx < m - 1 && beginy < n - 1){if (tmp[++beginx][++beginy] == 'Q'){return false;}}//左下beginx = i;beginy = j;while (beginx<m - 1 && beginy > 0){if (tmp[++beginx][--beginy] == 'Q'){return false;}}//左上beginx = i;beginy = j;while (beginx > 0 && beginy < n - 1){if (tmp[--beginx][++beginy] == 'Q'){return false;}}return true;}};程序的结果如下:
0 0
- 笔试题65. LeetCode OJ (52)
- 笔试题14. LeetCode OJ (1)
- 笔试题15. LeetCode OJ (2)
- 笔试题16. LeetCode OJ (3)
- 笔试题17. LeetCode OJ (4)
- 笔试题18. LeetCode OJ (7)
- 笔试题19. LeetCode OJ (5)
- 笔试题20. LeetCode OJ (6)
- 笔试题21 . LeetCode OJ (8)
- 笔试题22. LeetCode OJ (9)
- 笔试题23. LeetCode OJ (10)
- 笔试题24. LeetCode OJ (11)
- 笔试题25. LeetCode OJ (12)
- 笔试题26. LeetCode OJ (13)
- 笔试题27. LeetCode OJ (14)
- 笔试题28. LeetCode OJ (15)
- 笔试题29. LeetCode OJ (16)
- 笔试题30. LeetCode OJ (17)
- 如何才能让你的平台独占鳌头
- android studio layout中的preview异常
- Intellij idea 保存代码到Onenote空格消失问题
- vs2010串口开发随记(工具)
- javascript原型与原型链
- 笔试题65. LeetCode OJ (52)
- poj 3252 数位dp(dfs写法) 二进制0出现比1多的数字个数
- 《STL源码剖析》obj * volatile * my_free_list
- LinkedList用法详解
- log4j一段配置
- 我见过的最好的DataBinding解析
- yii2 实战教程之如何安装
- 接口隔离原则
- iOS 跳转系统设置页面