程序员面试金典——9.9n皇后问题
Solution1:我的答案,利用回溯法可做
我的答案就挺好,哈哈哈哈
class Queens {
public:
int nQueens(int n) {
// write code here
int times = 0;
vector<int> solutions;
my_backtrack(solutions, times, n);
return times;
}
//回溯法主体框架
void my_backtrack(vector<int> &solutions, int ×, int n) { //这里的solution传引用或值均可!
if(solutions.size() == n) {
times++;
return;
}
else if(solutions.size() < n) {
for(int i = 0; i < n; i++) {
solutions.push_back(i);
if(judgePoint(solutions))
my_backtrack(solutions, times, n);
solutions.pop_back();
}
}
}
//判断末元素是否合法
bool judgePoint(vector<int> &board) { //n是board中元素的个数
if (board.size() == 1)
return true;
else {
int n = board.size();
for (int i = 0; i < n - 1; i++) {
if(board[i] == board[n-1] || abs(i - (n-1)) == abs(board[i] - board[n-1]))
return false;
}
}
return true;
}
};