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

leetcode N-Queens

2014-06-09 21:39 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 
'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) {
vector<vector<string>> result;
vector<string> aresult(n,string(n,'.'));
sub(result,aresult,0,0,n);
return result;
}
bool place(vector<string> aresult,int kth,int pos){
int i;
bool flag=true;
for(i=0;i<kth;i++){
int ipos=aresult[i].find_first_of('Q');
if(ipos==pos||abs(i-kth)==abs(ipos-pos)){
flag=false;
return flag;
}
}
return flag;

}
void sub(vector<vector<string>> &result,vector<string> &aresult,int kth,int pos,int n){
if(kth>=n){     //因为是考虑第K个的位置,所以只有K大于n了,才能表明已经考虑了所有皇后。而且pos是将皇后放置在pos 这个位置
result.push_back(aresult);
return;
}
int i;
for(i=pos;i<n;i++){
if(place(aresult,kth,i)){
aresult[kth][i]='Q';
sub(result,aresult,kth+1,0,n);
aresult[kth][i]='.';
}
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: