您的位置:首页 > 产品设计 > UI/UE

[leetcode] N-Queens

2014-07-23 10:20 302 查看
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:
[
[".Q..",  // Solution 1
"...Q",
"Q...",
"..Q."],

["..Q.",  // Solution 2
"Q...",
"...Q",
".Q.."]
]

思路:深度搜索,属于经典问题了,定义两个数组,行数组和列数组,行数组用来存储该行摆放位置,列数组用来存储该列是否已经摆放过了,本代码参考了大神的代码
代码:

class Solution {
int row[1000],col[1000];
vector<vector<string> > res;
public:
vector<vector<string> > solveNQueens(int n) {
res.clear();
dfs(0,n);
return res;
}
void dfs(int step, int n){
int i,j;
if(step==n){
vector<string> rows;
for(i=0;i<n;i++){
string temp(n,'.');
temp[row[i]]='Q';
rows.push_back(temp);
}
res.push_back(rows);
}
for(i=0;i<n;i++){
if(col[i]==0){
for(j=0;j<step;j++){
if(abs(j-step)==abs(i-row[j])) break;//列之间的距离与行之间的距离相等;
}
if(j==step){
row[step]=i;
col[i]=1;
dfs(step+1,n);
row[step]=0;
col[i]=0;
}
}
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 算法