[CareerCup] 9.9 Eight Queens 八皇后问题
2015-09-29 11:17
543 查看
9.9 Write an algorithm to print all ways of arranging eight queens on an 8x8 chess board so that none of them share the same row, column or diagonal. In this case, "diagonal" means all diagonals, not just the two that bisect the board.
LeetCode上的原题,请参见我之前的博客N-Queens N皇后问题和N-Queens II N皇后问题之二。
LeetCode上的原题,请参见我之前的博客N-Queens N皇后问题和N-Queens II N皇后问题之二。
class Solution { public: vector<vector<int> > placeQueens(int n) { vector<vector<int> > res; vector<int> pos(n, -1); placeQueensDFS(pos, 0, res); return res; } void placeQueensDFS(vector<int> &pos, int row, vector<vector<int> > &res) { int n = pos.size(); if (row == n) res.push_back(pos); else { for (int col = 0; col < n; ++col) { if (isValid(pos, row, col)) { pos[row] = col; placeQueensDFS(pos, row + 1, res); pos[row] = -1; } } } } bool isValid(vector<int> &pos, int row, int col) { for (int i = 0; i < row; ++i) { if (col == pos[i] || abs(row - i) == abs(col - pos[i])) { return false; } } return true; } };
相关文章推荐
- Word Frequency
- I like UIView Class
- iOS开发之窥探UICollectionViewController(二) --详解CollectionView各种回调
- 在easyui datagrid中formatter数据后使用linkbutton
- 将UITableView的横线设置满屏幕
- iOS UI进阶-2.0 CALayer
- BlockingQueue
- [AY技术分享]WPF AYUI的高大上日历代码
- 现在,UICollectionViews有了简单的重排功能
- iOS UINavigationBar 使用总结
- 猫学习IOS(五岁以下儿童)UI之360其他下载管理器广场UI
- [iOS]NSURL,NSURLRequest, NSURLSession 和 NSURLSessionTask
- Priority Queue 优先级队列
- design pattern Builder 生成器设计模式
- Not a million dollars ——a certain kind of ingenuity, discipline, and proactivity that most people seem to lack
- 桌面/移动端 Ubuntu 将获重大 UI 升级
- UIViewContentMode各种模式的样式
- UITableView下拉刷新
- UI:归档、反归档、数据持久化
- gui画线和绘制鼠标