Files
Data-Structure/Algorithm/BackTracking/P1219 [USACO1.5] 八皇后 Checker Challenge.cpp
2025-09-21 12:21:50 +08:00

52 lines
875 B
C++

#include <iostream>
#include <set>
#include <vector>
using namespace std;
set<vector<int>> result;
bool check(const vector<int>& path, int pos) {
int row = path.size(); // 当前要放的行
for (int i = 0; i < row; i++) {
// 同列 或 在对角线上
if (path[i] == pos || abs(path[i] - pos) == row - i) {
return false;
}
}
return true;
}
void dfs(vector<int>& path_, int n){
if(path_.size() == n){
result.emplace(path_);
return;
}
int js = 0;
for(int i = 0; i < n; i++)
{
if(check(path_, i)){
js++;
path_.push_back(i);
dfs(path_, n);
path_.pop_back();
}
}
}
int main(){
int n;
cin >> n;
vector<int> path;
dfs(path, n);
auto it = result.begin();
for(int i = 0; i < 3; i++){
for(auto x : *it){
cout << x + 1 << " ";
}
cout << endl;
it++;
}
cout << result.size() << endl;
return 0;
}