[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
indicate a queen and an empty space respectively.
For example,
There exist two distinct solutions to the 4-queens puzzle:
思路:深度搜索,属于经典问题了,定义两个数组,行数组和列数组,行数组用来存储该行摆放位置,列数组用来存储该列是否已经摆放过了,本代码参考了大神的代码
代码:
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;
}
}
}
}
};
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_N-Queens
- [LeetCode] N-Queens
- [LeetCode]N-Queens
- LeetCode 51 N-Queens
- 52. N-Queens II Leetcode Python
- 【LeetCode】51.N-Queens(hard)解题报告
- LeetCode - N-Queens
- [LeetCode]N-Queens
- LeetCode No.51 N-Queens
- Leetcode: N-Queens
- LeetCode:N-Queens
- leetcode解题方案--051--N-Queens
- LeetCode--51. N-Queens
- Leetcode 51. N-Queens
- LeetCode——N-Queens
- LeetCode – Refresh – N-Queens
- LeetCode 051 N-Queens
- LeetCode:N-Queens
- Leetcode: N-Queens
- 51.leetcode N-Queens(hard)[递归回溯剪枝]