leetcode 050 —— N-Queens
2015-07-23 19:09
363 查看
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
indicate a queen and an empty space respectively.
For example,
There exist two distinct solutions to the 4-queens puzzle:
直接上代码
class Solution {
public:
vector<vector<string> > solveNQueens(int n) {
//string s( n, '.' );
vector<string> path(n, string (n, '.'));
vector<vector<string> > res;
create(0, n, path, res);
return res;
}
bool isValid(int v, int s, int n, vector<string> &path){ //第v行的第s列 是否有效
int vv, ss;
for (int i = 0; i < v; i++){
vv = i;
ss = path[vv].find('Q');
if (ss == s)
return false;
if ((v - vv) == (s - ss))
return false;
if ((v - vv) == (ss - s))
return false;
}
return true;
}
void create(int level, int n, vector<string> &path, vector<vector<string> > &res){
if (level == n){
res.push_back(path);
return;
}
for (int i = 0; i < n; i++){
if (isValid(level, i, n, path)){
path[level][i] = 'Q';
create(level + 1, n, path, res);
path[level][i] = '.';
}
}
}
};
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.."] ]
直接上代码
class Solution {
public:
vector<vector<string> > solveNQueens(int n) {
//string s( n, '.' );
vector<string> path(n, string (n, '.'));
vector<vector<string> > res;
create(0, n, path, res);
return res;
}
bool isValid(int v, int s, int n, vector<string> &path){ //第v行的第s列 是否有效
int vv, ss;
for (int i = 0; i < v; i++){
vv = i;
ss = path[vv].find('Q');
if (ss == s)
return false;
if ((v - vv) == (s - ss))
return false;
if ((v - vv) == (ss - s))
return false;
}
return true;
}
void create(int level, int n, vector<string> &path, vector<vector<string> > &res){
if (level == n){
res.push_back(path);
return;
}
for (int i = 0; i < n; i++){
if (isValid(level, i, n, path)){
path[level][i] = 'Q';
create(level + 1, n, path, res);
path[level][i] = '.';
}
}
}
};
相关文章推荐
- BZOJ 1367 [Baltic2004]sequence 可并堆
- OPEN(SAP) UI5 学习入门系列之一:扫盲与热身(上)
- WPF 开启多线程刷新UI 界面
- iphone的系统信息使用[UIDevice currentDevice]
- 建议SQLite操作使用rawQuery方法
- OC类 之 NSData NSDate NSSet NSNumber NSValue
- 多校2 1002 Buildings
- NSNumber,NSValue
- F - True Liars - poj1417(背包+并查集)
- 2015多校联合训练赛hdu 5301 Buildings 2015 Multi-University Training Contest 2 简单题
- OPEN(SAP) UI5 学习入门系列之一:扫盲与热身(上)
- Masonry与UITableView+FDTemplateLayoutCell搭配使用
- iOS总结控件三(UIView)
- MongoVUE Group分组统计查询
- requireJS
- requireJS
- mongo vue的常用操作
- BUILD_BUG_ON
- 设置UIlabel的行高
- ocp 047-40 User OE, the owner of the ORDERS table, issues the following command: