八皇后的意思是,每行只能有一个,每个对角线只能有一个,每一列只能有一个,我们可以dfs遍历每种情况,每行填一个,通过对角线和列的限制来进行剪枝
话不多说,我们来实现一下代码
#include <iostream>
#include <vector>
using namespace std;
const int N = 50;
int n;
int ret;
vector<int> path;
bool col[N],st1[N*2],st2[N*2];void dfs(int pos)
{if(pos>n){if(ret>=3);else{for(auto&e : path){cout << e << " ";}cout << endl;}ret++;return;}for(int j = 1;j<=n;j++){if(col[j]||st1[pos-j+n]||st2[pos+j])continue;col[j]=st1[pos-j+n]=st2[pos+j] = true;path.push_back(j);dfs(pos+1);col[j]=st1[pos-j+n]=st2[pos+j] = false;path.pop_back();}
}
int main()
{cin >> n;dfs(1);cout << ret << endl;return 0;
}