leetcode No51. N-Queens
2016-07-16 16:06
405 查看
Question:
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:
Algorithm:
由鹊巢原理,每一层一定有一个Queen,所以不妨从第一行往下试探,用一个数组cur存放Queen的列标。首先需要一个判断是否合法的函数isVaild判断是否和之前的Queen冲突,由于是逐行试探,所以不需要判断行号,只需判断列号和斜线。
从第一行往下试探,如果是合法的,继续往下试探,一直到n都是合法的那么就是一个解;试探过程中一旦不合法,停止。
Accepted Code:
class Solution { vector<vector<string>> res; public: vector<vector<string>> solveNQueens(int n) { //有很多解 vector<int> v(n); result(v,n,0); return res; } private: bool isValid (vector<int> &cur,int c) //cur为记录的列数数组,c为当前行数,cur[c]为当前列数 { for(int i=0;i<c;i++) //只需判断列数和斜线 { if(cur[i]==cur[c]||abs(cur[c]-cur[i])==abs(c-i)) return false; } return true; } void result(vector<int> &cur,int n,int c) { if(c==n) //因为c是从0开始的,所以c==n时,已经有n个数了 { vector<string> temp(n,string(n,'.')); for(int i=0;i<n;i++) { temp[i][cur[i]]='Q'; } res.push_back(temp); } for(cur[c]=0;cur[c]<n;cur[c]++) { if(isValid(cur,c)) { cur.push_back(cur[c]); result(cur,n,c+1); } } } };
相关文章推荐
- UITableView的使用样例(简易向)
- Android uiautomator实例使用
- Cannot find D:\Program Files (x86)\Android\android-sdk\tools\ant\uibuild.xml
- 关于iOS 中UIViewController的生命周期以及相关视图(View)的探讨
- PriorityQueue类源码解析
- iOS-- UIimageView详解
- 374. Guess Number Higher or Lower
- UIScrollView的子视图的起点不是左上角
- IOS之UIScrollView分页无限循环滚动框架
- hdu_1711Number Sequence(kmp)
- mysql5.7设置简单密码报错ERROR 1819 (HY000): Your password does not satisfy the current policy requirements
- 利用弹窗来更改表视图中的数据
- java学习总结(16.07.16)StringBuffer类和StringBuilderr类
- iOS dispatch_set_target_queue 详解
- 加载外部obj(gcpuid.obj)文件的方法
- android uiautomator自动化测试记录
- ArrayDeque类源码解析
- stl_tree.h/insert_unique()
- Re: Programming in C with Bluetooth Sockets
- 7、easyui 表单