N-Queens
2015-08-04 22:10
281 查看
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
For example,
There exist two distinct solutions to the 4-queens puzzle:
Solution:
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:
[ [".Q..", // Solution 1 "...Q", "Q...", "..Q."], ["..Q.", // Solution 2 "Q...", "...Q", ".Q.."] ]
Solution:
class Solution { private: vector<vector<string> > res; vector<int> vi; public: bool isValued(int k) { for(int i = 0; i < k; ++i) { if(vi[i] == vi[k] || abs(vi[i] - vi[k]) == abs(i - k)) { return false; } } return true; } void dfs(int depth, int n) { if(depth == n) { vector<string> vs(n); for(int i = 0; i < n; ++i) { string str(n, '.'); str[vi[i]] = 'Q'; vs[i] = str; } res.push_back(vs); } else { for(int i = 0; i < n; ++i) { vi[depth] = i; if(isValued(depth)) dfs(depth + 1, n); } } } vector<vector<string>> solveNQueens(int n) { vi.resize(n); res.clear(); dfs(0, n); return res; } };
相关文章推荐
- UI04_UIDelegate
- VistualStudio 2005 设置PowerBuilder12.5 PBNI编绎命令行。
- UI 04 target...action 设计模式
- iOS开发——UI进阶篇(十六)Quartz2D实战小例子
- HDU1.2.6 Buildings
- UVA1152 4Values whose Sum is 0
- HDU 5301 Buildings
- DPDK 的 uio 以及 PMD 机制的实现
- minicom question
- 记录一下iOS的几个UIView的方法
- UI 03 自定义的Label-TextField视图 --- LTView
- iOS开发——UI进阶篇(十五)Quartz2D介绍
- UISwitch设置代理人 帮助实现变换背景颜色
- ios学习(UITabBarController)
- poj 2299 Ultra-QuickSort (树状数组+离散化)
- HD1047 Integer Inquiry 【大数问题】
- iOS UI04_Target-Action
- BIM建筑信息模型(Building Information Modeling)
- UI 03 UIViewController (视图控制器)的7个方法与视图的跳转
- Disque: antirez开发的开源分布式内存作业队列