thanks to the video of stanford cs106b lecture 10 by Julie Zelenski for the nice explanation of recursion and backtracking, highly recommended.
//N-Queens(12ms)
class Solution {
vector<vector<string>> ans;
int N;
//int numofsol;
void AddTo_ans(string &conf) {
vector<string> vecstrtmp;
string strtmp(N,‘.‘);
for(auto ind: conf) {
vecstrtmp.push_back(strtmp);
vecstrtmp.back()[(size_t)ind-1]=‘Q‘;
}
ans.push_back(vector<string>());
ans.back().swap(vecstrtmp);
}
void RecListNQueens(string soFar, string rest) {
if(rest.empty()) {
//++numofsol;
AddTo_ans(soFar);
}
else {
int i,j,len=soFar.size(), flag;
for(i=0;i<rest.size();++i) {
for(j=0;j<len;++j) {
flag=1;
if(soFar[j]-rest[i]==len-j || soFar[j]-rest[i]==j-len) {
flag=0; break;
}
}
if(flag) RecListNQueens(soFar+rest[i],rest.substr(0,i)+rest.substr(i+1));
}
}
}
public:
vector<vector<string>> solveNQueens(int n) {
ans.clear();
//numofsol=0;
N=n;
string str;
for(int i=1;i<=n;++i) str.push_back(i);
RecListNQueens("", str);
return ans;
}
};
//with a tiny modification,
//N-Queens II (8ms)
class Solution {
//vector<vector<string>> ans;
int N;
int numofsol;
/*void AddTo_ans(string &conf) {
vector<string> vecstrtmp;
string strtmp(N,‘.‘);
for(auto ind: conf) {
vecstrtmp.push_back(strtmp);
vecstrtmp.back()[(size_t)ind-1]=‘Q‘;
}
ans.push_back(vector<string>());
ans.back().swap(vecstrtmp);
}*/
void RecListNQueens(string soFar, string rest) {
if(rest.empty()) {
++numofsol;
//AddTo_ans(soFar);
}
else {
int i,j,len=soFar.size(), flag;
for(i=0;i<rest.size();++i) {
for(j=0;j<len;++j) {
flag=1;
if(soFar[j]-rest[i]==len-j || soFar[j]-rest[i]==j-len) {
flag=0; break;
}
}
if(flag) RecListNQueens(soFar+rest[i],rest.substr(0,i)+rest.substr(i+1));
}
}
}
public:
int totalNQueens(int n) {
//ans.clear();
numofsol=0;
N=n;
string str;
for(int i=1;i<=n;++i) str.push_back(i);
RecListNQueens("", str);
return numofsol;
}
};
版权声明:本文为博主原创文章,未经博主允许不得转载。
leetcode N-Queens/N-Queens II, backtracking, C++
原文地址:http://blog.csdn.net/qeatzy/article/details/46811451