51. N-Queens
来源:互联网 发布:制作编程语言 编辑:程序博客网 时间:2024/06/01 19:26
题目: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.
n皇后问题就是在n×n的棋盘里放置n个棋子,每行每列每条对角线都只能出现1个棋子。现在给定一个整数n,要求返回所有n×n棋盘的解。
思路:显然枚举所有情况肯定能解决问题,但是时间复杂度是O(n!),会超时。像这种图论的题,一般用深搜就可以解决了。从第一行开始的某一个位置放置棋子,接着搜索下一行,在下一行找到一个满足不发生冲突条件的位置放置棋子,再接着搜索下一行。直到搜索到第n行的时候也能找到一个满足条件的棋子,这个时候就找到一个解了。用一个数组来存放每一行棋子的列数,就可以转换成题目要求输出的结果。检查满足条件的时候,要对每行每列每个对角线都检查,因为这是按行搜索的,所以肯定每行之间不会有冲突,只需要检查每列和每个对角线,这时候用存放结果的数组判断就很方便了。
class Solution {private: vector<vector<string>> res;//存放最终结果的数组public: vector<vector<string>> solveNQueens(int n) { vector<int> sol(n);//存放临时结果的数组 solve(sol, n, 0);//DFS return res; } void solve(vector<int> &sol, int n, int cur) { if(n == cur)//搜索到第n行的时候,就可以存放结果了 { vector<string> temp(n, string(n,'.')); for(int i = 0; i < n; ++i) temp[i][sol[i]] = 'Q'; res.push_back(temp); } else { for(sol[cur] = 0; sol[cur] < n; ++sol[cur])//对第cur行的每个位置进行搜索 if(can(sol,n,cur))//如果满足条件,搜索下一行 solve(sol, n, cur+1); } } bool can(vector<int> &sol,int n, int cur) { int now = sol[cur]; for(int i = 0; i < cur; ++i) { int pre = sol[i]; if(pre == now || abs(pre-now) == abs(i-cur))//判断每列和每个对角线是否冲突 return false; } return true; }};
阅读全文
0 0
- 51. N-Queens && 52. N-Queens II
- 51. N-Queens/52. N-Queens II
- LeetCode 51. N-Queens
- LeetCode --- 51. N-Queens
- LeetCode 51.N-Queens
- [Leetcode] 51. N-Queens
- 51.N-Queens
- [leetcode] 51.N-Queens
- 51. N-Queens
- [leetcode] 51. N-Queens
- LeetCode 51. N-Queens
- 51. N-Queens
- leetcode 51. N-Queens
- 【LeetCode】51. N-Queens
- leetcode 51. N-Queens
- LeetCode 51. N-Queens
- 51. N-Queens
- LeetCode 51. N-Queens
- (封装)C# 功能帮助类(CommonHelper) 一些常用的公共方法!!!
- LeetCode 56 Merge Intervals
- 你们都是怎么学Python 的?
- 几行命令解决adb无法连接Android手机的问题
- 第十一章 缓存内容
- 51. N-Queens
- ThreadLocal与Spring
- 状态压缩DP总结【POJ3254】【POJ1185】【POJ3311】【HDU3001】【POJ2288】【ZOJ4257】【POJ2411】【HDU3681】
- 任务一
- Eclipse简单分包65535问题
- list -- set方法——替换列表中指定位置的元素
- 第十二章 构建API
- 集合框架源码学习——ArrayList
- Web.xml配置详解之context-param