题意:经典的八皇后问题
解法:
采用朴素的每一次放置都与前面的所有行进行比较,在N =13的时候时间会爆掉
《入门经典》上提供的方法很经典,vis数组的使用,具体见《入门经典》125页
/* ID:lsswxr1 PROG:checker LANG:C++ */ #include<iostream> #include<fstream> #include<cmath> #include<cstring> using namespace std; #define maxn 15 ifstream fin("checker.in"); ofstream fout("checker.out"); int N, tot; int outputNums; int curPuts[maxn]; int vis[30][30]; void dfs(int cur) {if (cur == N){tot++;outputNums++;if (outputNums > 3){return;}for (int i = 0; i < N; i++){if (i == 0){fout << curPuts[i] + 1;}else{fout << " " << curPuts[i] + 1;}}fout << endl;return;}for (int i = 0; i < N; i++){if (!vis[0][i] && !vis[1][cur + i] && !vis[2][cur - i + N]){curPuts[cur] = i;vis[0][i] = vis[1][cur + i] = vis[2][cur - i + N] = 1;dfs(cur + 1);vis[0][i] = vis[1][cur + i] = vis[2][cur - i + N] = 0;}}}int main() {fin >> N;tot = 0;memset(vis, 0, sizeof(vis));memset(curPuts, 0, sizeof(curPuts));dfs(0);fout << tot << endl;//cout<<ans<<endl;return 0; }